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/>.
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
28 from samba
.descriptor
import get_wellknown_sds
, get_diff_sds
31 class dbcheck(object):
32 """check a SAM database for errors"""
34 def __init__(self
, samdb
, samdb_schema
=None, verbose
=False, fix
=False,
35 yes
=False, quiet
=False, in_transaction
=False,
36 reset_well_known_acls
=False):
38 self
.dict_oid_name
= None
39 self
.samdb_schema
= (samdb_schema
or samdb
)
40 self
.verbose
= verbose
44 self
.remove_all_unknown_attributes
= False
45 self
.remove_all_empty_attributes
= False
46 self
.fix_all_normalisation
= False
47 self
.fix_all_DN_GUIDs
= False
48 self
.fix_all_binary_dn
= False
49 self
.remove_all_deleted_DN_links
= False
50 self
.fix_all_target_mismatch
= False
51 self
.fix_all_metadata
= False
52 self
.fix_time_metadata
= False
53 self
.fix_all_missing_backlinks
= False
54 self
.fix_all_orphaned_backlinks
= False
55 self
.fix_rmd_flags
= False
56 self
.fix_ntsecuritydescriptor
= False
57 self
.seize_fsmo_role
= False
58 self
.move_to_lost_and_found
= False
59 self
.fix_instancetype
= False
60 self
.reset_well_known_acls
= reset_well_known_acls
61 self
.reset_all_well_known_acls
= False
62 self
.in_transaction
= in_transaction
63 self
.infrastructure_dn
= ldb
.Dn(samdb
, "CN=Infrastructure," + samdb
.domain_dn())
64 self
.naming_dn
= ldb
.Dn(samdb
, "CN=Partitions,%s" % samdb
.get_config_basedn())
65 self
.schema_dn
= samdb
.get_schema_basedn()
66 self
.rid_dn
= ldb
.Dn(samdb
, "CN=RID Manager$,CN=System," + samdb
.domain_dn())
67 self
.ntds_dsa
= ldb
.Dn(samdb
, samdb
.get_dsServiceName())
68 self
.class_schemaIDGUID
= {}
69 self
.wellknown_sds
= get_wellknown_sds(self
.samdb
)
73 res
= samdb
.search(base
="CN=DnsAdmins,CN=Users,%s" % samdb
.domain_dn(), scope
=ldb
.SCOPE_BASE
,
75 dnsadmins_sid
= ndr_unpack(security
.dom_sid
, res
[0]["objectSid"][0])
76 self
.name_map
['DnsAdmins'] = str(dnsadmins_sid
)
77 except ldb
.LdbError
, (enum
, estr
):
78 if enum
!= ldb
.ERR_NO_SUCH_OBJECT
:
82 res
= self
.samdb
.search(base
=self
.ntds_dsa
, scope
=ldb
.SCOPE_BASE
, attrs
=['msDS-hasMasterNCs', 'hasMasterNCs'])
83 if "msDS-hasMasterNCs" in res
[0]:
84 self
.write_ncs
= res
[0]["msDS-hasMasterNCs"]
86 # If the Forest Level is less than 2003 then there is no
87 # msDS-hasMasterNCs, so we fall back to hasMasterNCs
88 # no need to merge as all the NCs that are in hasMasterNCs must
89 # also be in msDS-hasMasterNCs (but not the opposite)
90 if "hasMasterNCs" in res
[0]:
91 self
.write_ncs
= res
[0]["hasMasterNCs"]
96 def check_database(self
, DN
=None, scope
=ldb
.SCOPE_SUBTREE
, controls
=[], attrs
=['*']):
97 '''perform a database check, returning the number of errors found'''
99 res
= self
.samdb
.search(base
=DN
, scope
=scope
, attrs
=['dn'], controls
=controls
)
100 self
.report('Checking %u objects' % len(res
))
104 error_count
+= self
.check_object(object.dn
, attrs
=attrs
)
107 error_count
+= self
.check_rootdse()
109 if error_count
!= 0 and not self
.fix
:
110 self
.report("Please use --fix to fix these errors")
112 self
.report('Checked %u objects (%u errors)' % (len(res
), error_count
))
115 def report(self
, msg
):
116 '''print a message unless quiet is set'''
120 def confirm(self
, msg
, allow_all
=False, forced
=False):
121 '''confirm a change'''
128 return common
.confirm(msg
, forced
=forced
, allow_all
=allow_all
)
130 ################################################################
131 # a local confirm function with support for 'all'
132 def confirm_all(self
, msg
, all_attr
):
133 '''confirm a change with support for "all" '''
138 if getattr(self
, all_attr
) == 'NONE':
140 if getattr(self
, all_attr
) == 'ALL':
144 c
= common
.confirm(msg
, forced
=forced
, allow_all
=True)
146 setattr(self
, all_attr
, 'ALL')
149 setattr(self
, all_attr
, 'NONE')
153 def do_modify(self
, m
, controls
, msg
, validate
=True):
154 '''perform a modify with optional verbose output'''
156 self
.report(self
.samdb
.write_ldif(m
, ldb
.CHANGETYPE_MODIFY
))
158 controls
= controls
+ ["local_oid:%s:0" % dsdb
.DSDB_CONTROL_DBCHECK
]
159 self
.samdb
.modify(m
, controls
=controls
, validate
=validate
)
160 except Exception, err
:
161 self
.report("%s : %s" % (msg
, err
))
165 def do_rename(self
, from_dn
, to_rdn
, to_base
, controls
, msg
):
166 '''perform a modify with optional verbose output'''
168 self
.report("""dn: %s
172 newSuperior: %s""" % (str(from_dn
), str(to_rdn
), str(to_base
)))
174 to_dn
= to_rdn
+ to_base
175 controls
= controls
+ ["local_oid:%s:0" % dsdb
.DSDB_CONTROL_DBCHECK
]
176 self
.samdb
.rename(from_dn
, to_dn
, controls
=controls
)
177 except Exception, err
:
178 self
.report("%s : %s" % (msg
, err
))
182 def err_empty_attribute(self
, dn
, attrname
):
183 '''fix empty attributes'''
184 self
.report("ERROR: Empty attribute %s in %s" % (attrname
, dn
))
185 if not self
.confirm_all('Remove empty attribute %s from %s?' % (attrname
, dn
), 'remove_all_empty_attributes'):
186 self
.report("Not fixing empty attribute %s" % attrname
)
191 m
[attrname
] = ldb
.MessageElement('', ldb
.FLAG_MOD_DELETE
, attrname
)
192 if self
.do_modify(m
, ["relax:0", "show_recycled:1"],
193 "Failed to remove empty attribute %s" % attrname
, validate
=False):
194 self
.report("Removed empty attribute %s" % attrname
)
196 def err_normalise_mismatch(self
, dn
, attrname
, values
):
197 '''fix attribute normalisation errors'''
198 self
.report("ERROR: Normalisation error for attribute %s in %s" % (attrname
, dn
))
201 normalised
= self
.samdb
.dsdb_normalise_attributes(
202 self
.samdb_schema
, attrname
, [val
])
203 if len(normalised
) != 1:
204 self
.report("Unable to normalise value '%s'" % val
)
205 mod_list
.append((val
, ''))
206 elif (normalised
[0] != val
):
207 self
.report("value '%s' should be '%s'" % (val
, normalised
[0]))
208 mod_list
.append((val
, normalised
[0]))
209 if not self
.confirm_all('Fix normalisation for %s from %s?' % (attrname
, dn
), 'fix_all_normalisation'):
210 self
.report("Not fixing attribute %s" % attrname
)
215 for i
in range(0, len(mod_list
)):
216 (val
, nval
) = mod_list
[i
]
217 m
['value_%u' % i
] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
219 m
['normv_%u' % i
] = ldb
.MessageElement(nval
, ldb
.FLAG_MOD_ADD
,
222 if self
.do_modify(m
, ["relax:0", "show_recycled:1"],
223 "Failed to normalise attribute %s" % attrname
,
225 self
.report("Normalised attribute %s" % attrname
)
227 def err_normalise_mismatch_replace(self
, dn
, attrname
, values
):
228 '''fix attribute normalisation errors'''
229 normalised
= self
.samdb
.dsdb_normalise_attributes(self
.samdb_schema
, attrname
, values
)
230 self
.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname
, dn
))
231 self
.report("Values/Order of values do/does not match: %s/%s!" % (values
, list(normalised
)))
232 if list(normalised
) == values
:
234 if not self
.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname
, dn
), 'fix_all_normalisation'):
235 self
.report("Not fixing attribute '%s'" % attrname
)
240 m
[attrname
] = ldb
.MessageElement(normalised
, ldb
.FLAG_MOD_REPLACE
, attrname
)
242 if self
.do_modify(m
, ["relax:0", "show_recycled:1"],
243 "Failed to normalise attribute %s" % attrname
,
245 self
.report("Normalised attribute %s" % attrname
)
247 def is_deleted_objects_dn(self
, dsdb_dn
):
248 '''see if a dsdb_Dn is the special Deleted Objects DN'''
249 return dsdb_dn
.prefix
== "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
251 def err_deleted_dn(self
, dn
, attrname
, val
, dsdb_dn
, correct_dn
):
252 """handle a DN pointing to a deleted object"""
253 self
.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname
, dn
, val
))
254 self
.report("Target GUID points at deleted DN %s" % correct_dn
)
255 if not self
.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
256 self
.report("Not removing")
260 m
['old_value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
261 if self
.do_modify(m
, ["show_recycled:1", "local_oid:%s:0" % dsdb
.DSDB_CONTROL_DBCHECK
],
262 "Failed to remove deleted DN attribute %s" % attrname
):
263 self
.report("Removed deleted DN on attribute %s" % attrname
)
265 def err_missing_dn_GUID(self
, dn
, attrname
, val
, dsdb_dn
):
266 """handle a missing target DN (both GUID and DN string form are missing)"""
267 # check if its a backlink
268 linkID
= self
.samdb_schema
.get_linkId_from_lDAPDisplayName(attrname
)
269 if (linkID
& 1 == 0) and str(dsdb_dn
).find('DEL\\0A') == -1:
270 self
.report("Not removing dangling forward link")
272 self
.err_deleted_dn(dn
, attrname
, val
, dsdb_dn
, dsdb_dn
)
274 def err_incorrect_dn_GUID(self
, dn
, attrname
, val
, dsdb_dn
, errstr
):
275 """handle a missing GUID extended DN component"""
276 self
.report("ERROR: %s component for %s in object %s - %s" % (errstr
, attrname
, dn
, val
))
277 controls
=["extended_dn:1:1", "show_recycled:1"]
279 res
= self
.samdb
.search(base
=str(dsdb_dn
.dn
), scope
=ldb
.SCOPE_BASE
,
280 attrs
=[], controls
=controls
)
281 except ldb
.LdbError
, (enum
, estr
):
282 self
.report("unable to find object for DN %s - (%s)" % (dsdb_dn
.dn
, estr
))
283 self
.err_missing_dn_GUID(dn
, attrname
, val
, dsdb_dn
)
286 self
.report("unable to find object for DN %s" % dsdb_dn
.dn
)
287 self
.err_missing_dn_GUID(dn
, attrname
, val
, dsdb_dn
)
289 dsdb_dn
.dn
= res
[0].dn
291 if not self
.confirm_all('Change DN to %s?' % str(dsdb_dn
), 'fix_all_DN_GUIDs'):
292 self
.report("Not fixing %s" % errstr
)
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
)
299 if self
.do_modify(m
, ["show_recycled:1"],
300 "Failed to fix %s on attribute %s" % (errstr
, attrname
)):
301 self
.report("Fixed %s on attribute %s" % (errstr
, attrname
))
303 def err_incorrect_binary_dn(self
, dn
, attrname
, val
, dsdb_dn
, errstr
):
304 """handle an incorrect binary DN component"""
305 self
.report("ERROR: %s binary component for %s in object %s - %s" % (errstr
, attrname
, dn
, val
))
306 controls
=["extended_dn:1:1", "show_recycled:1"]
308 if not self
.confirm_all('Change DN to %s?' % str(dsdb_dn
), 'fix_all_binary_dn'):
309 self
.report("Not fixing %s" % errstr
)
313 m
['old_value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
314 m
['new_value'] = ldb
.MessageElement(str(dsdb_dn
), ldb
.FLAG_MOD_ADD
, attrname
)
316 if self
.do_modify(m
, ["show_recycled:1"],
317 "Failed to fix %s on attribute %s" % (errstr
, attrname
)):
318 self
.report("Fixed %s on attribute %s" % (errstr
, attrname
))
320 def err_dn_target_mismatch(self
, dn
, attrname
, val
, dsdb_dn
, correct_dn
, errstr
):
321 """handle a DN string being incorrect"""
322 self
.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname
, dn
, val
))
323 dsdb_dn
.dn
= correct_dn
325 if not self
.confirm_all('Change DN to %s?' % str(dsdb_dn
), 'fix_all_target_mismatch'):
326 self
.report("Not fixing %s" % errstr
)
330 m
['old_value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
331 m
['new_value'] = ldb
.MessageElement(str(dsdb_dn
), ldb
.FLAG_MOD_ADD
, attrname
)
332 if self
.do_modify(m
, ["show_recycled:1"],
333 "Failed to fix incorrect DN string on attribute %s" % attrname
):
334 self
.report("Fixed incorrect DN string on attribute %s" % (attrname
))
336 def err_unknown_attribute(self
, obj
, attrname
):
337 '''handle an unknown attribute error'''
338 self
.report("ERROR: unknown attribute '%s' in %s" % (attrname
, obj
.dn
))
339 if not self
.confirm_all('Remove unknown attribute %s' % attrname
, 'remove_all_unknown_attributes'):
340 self
.report("Not removing %s" % attrname
)
344 m
['old_value'] = ldb
.MessageElement([], ldb
.FLAG_MOD_DELETE
, attrname
)
345 if self
.do_modify(m
, ["relax:0", "show_recycled:1"],
346 "Failed to remove unknown attribute %s" % attrname
):
347 self
.report("Removed unknown attribute %s" % (attrname
))
349 def err_missing_backlink(self
, obj
, attrname
, val
, backlink_name
, target_dn
):
350 '''handle a missing backlink value'''
351 self
.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name
, target_dn
, attrname
, obj
.dn
))
352 if not self
.confirm_all('Fix missing backlink %s' % backlink_name
, 'fix_all_missing_backlinks'):
353 self
.report("Not fixing missing backlink %s" % backlink_name
)
357 m
['old_value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
358 m
['new_value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_ADD
, attrname
)
359 if self
.do_modify(m
, ["show_recycled:1"],
360 "Failed to fix missing backlink %s" % backlink_name
):
361 self
.report("Fixed missing backlink %s" % (backlink_name
))
363 def err_incorrect_rmd_flags(self
, obj
, attrname
, revealed_dn
):
364 '''handle a incorrect RMD_FLAGS value'''
365 rmd_flags
= int(revealed_dn
.dn
.get_extended_component("RMD_FLAGS"))
366 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()))
367 if not self
.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags
, 'fix_rmd_flags'):
368 self
.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags
)
372 m
['old_value'] = ldb
.MessageElement(str(revealed_dn
), ldb
.FLAG_MOD_DELETE
, attrname
)
373 if self
.do_modify(m
, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
374 "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags
):
375 self
.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags
))
377 def err_orphaned_backlink(self
, obj
, attrname
, val
, link_name
, target_dn
):
378 '''handle a orphaned backlink value'''
379 self
.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname
, obj
.dn
, link_name
, target_dn
))
380 if not self
.confirm_all('Remove orphaned backlink %s' % link_name
, 'fix_all_orphaned_backlinks'):
381 self
.report("Not removing orphaned backlink %s" % link_name
)
385 m
['value'] = ldb
.MessageElement(val
, ldb
.FLAG_MOD_DELETE
, attrname
)
386 if self
.do_modify(m
, ["show_recycled:1", "relax:0"],
387 "Failed to fix orphaned backlink %s" % link_name
):
388 self
.report("Fixed orphaned backlink %s" % (link_name
))
390 def err_no_fsmoRoleOwner(self
, obj
):
391 '''handle a missing fSMORoleOwner'''
392 self
.report("ERROR: fSMORoleOwner not found for role %s" % (obj
.dn
))
393 res
= self
.samdb
.search("",
394 scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
396 serviceName
= res
[0]["dsServiceName"][0]
397 if not self
.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj
.dn
, serviceName
), 'seize_fsmo_role'):
398 self
.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj
.dn
, serviceName
))
402 m
['value'] = ldb
.MessageElement(serviceName
, ldb
.FLAG_MOD_ADD
, 'fSMORoleOwner')
403 if self
.do_modify(m
, [],
404 "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj
.dn
, serviceName
)):
405 self
.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj
.dn
, serviceName
))
407 def err_missing_parent(self
, obj
):
408 '''handle a missing parent'''
409 self
.report("ERROR: parent object not found for %s" % (obj
.dn
))
410 if not self
.confirm_all('Move object %s into LostAndFound?' % (obj
.dn
), 'move_to_lost_and_found'):
411 self
.report('Not moving object %s into LostAndFound' % (obj
.dn
))
414 keep_transaction
= True
415 self
.samdb
.transaction_start()
417 nc_root
= self
.samdb
.get_nc_root(obj
.dn
);
418 lost_and_found
= self
.samdb
.get_wellknown_dn(nc_root
, dsdb
.DS_GUID_LOSTANDFOUND_CONTAINER
)
419 new_dn
= ldb
.Dn(self
.samdb
, str(obj
.dn
))
420 new_dn
.remove_base_components(len(new_dn
) - 1)
421 if self
.do_rename(obj
.dn
, new_dn
, lost_and_found
, ["show_deleted:0", "relax:0"],
422 "Failed to rename object %s into lostAndFound at %s" % (obj
.dn
, new_dn
+ lost_and_found
)):
423 self
.report("Renamed object %s into lostAndFound at %s" % (obj
.dn
, new_dn
+ lost_and_found
))
427 m
['lastKnownParent'] = ldb
.MessageElement(str(obj
.dn
.parent()), ldb
.FLAG_MOD_REPLACE
, 'lastKnownParent')
429 if self
.do_modify(m
, [],
430 "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn
+ lost_and_found
)):
431 self
.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn
+ lost_and_found
))
432 keep_transaction
= True
434 self
.samdb
.transaction_cancel()
438 self
.samdb
.transaction_commit()
440 self
.samdb
.transaction_cancel()
443 def err_wrong_instancetype(self
, obj
, calculated_instancetype
):
444 '''handle a wrong instanceType'''
445 self
.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj
["instanceType"], obj
.dn
, calculated_instancetype
))
446 if not self
.confirm_all('Change instanceType from %s to %d on %s?' % (obj
["instanceType"], calculated_instancetype
, obj
.dn
), 'fix_instancetype'):
447 self
.report('Not changing instanceType from %s to %d on %s' % (obj
["instanceType"], calculated_instancetype
, obj
.dn
))
452 m
['value'] = ldb
.MessageElement(str(calculated_instancetype
), ldb
.FLAG_MOD_REPLACE
, 'instanceType')
453 if self
.do_modify(m
, ["local_oid:%s:0" % dsdb
.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA
],
454 "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj
.dn
, calculated_instancetype
)):
455 self
.report("Corrected instancetype on %s by setting instanceType=%d" % (obj
.dn
, calculated_instancetype
))
457 def find_revealed_link(self
, dn
, attrname
, guid
):
458 '''return a revealed link in an object'''
459 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
, attrs
=[attrname
],
460 controls
=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
461 syntax_oid
= self
.samdb_schema
.get_syntax_oid_from_lDAPDisplayName(attrname
)
462 for val
in res
[0][attrname
]:
463 dsdb_dn
= dsdb_Dn(self
.samdb
, val
, syntax_oid
)
464 guid2
= dsdb_dn
.dn
.get_extended_component("GUID")
469 def check_dn(self
, obj
, attrname
, syntax_oid
):
470 '''check a DN attribute for correctness'''
472 for val
in obj
[attrname
]:
473 dsdb_dn
= dsdb_Dn(self
.samdb
, val
, syntax_oid
)
475 # all DNs should have a GUID component
476 guid
= dsdb_dn
.dn
.get_extended_component("GUID")
479 self
.err_incorrect_dn_GUID(obj
.dn
, attrname
, val
, dsdb_dn
,
483 guidstr
= str(misc
.GUID(guid
))
485 attrs
= ['isDeleted']
487 if (str(attrname
).lower() == 'msds-hasinstantiatedncs') and (obj
.dn
== self
.ntds_dsa
):
488 fixing_msDS_HasInstantiatedNCs
= True
489 attrs
.append("instanceType")
491 fixing_msDS_HasInstantiatedNCs
= False
493 linkID
= self
.samdb_schema
.get_linkId_from_lDAPDisplayName(attrname
)
494 reverse_link_name
= self
.samdb_schema
.get_backlink_from_lDAPDisplayName(attrname
)
495 if reverse_link_name
is not None:
496 attrs
.append(reverse_link_name
)
498 # check its the right GUID
500 res
= self
.samdb
.search(base
="<GUID=%s>" % guidstr
, scope
=ldb
.SCOPE_BASE
,
501 attrs
=attrs
, controls
=["extended_dn:1:1", "show_recycled:1"])
502 except ldb
.LdbError
, (enum
, estr
):
504 self
.err_incorrect_dn_GUID(obj
.dn
, attrname
, val
, dsdb_dn
, "incorrect GUID")
507 if fixing_msDS_HasInstantiatedNCs
:
508 dsdb_dn
.prefix
= "B:8:%08X:" % int(res
[0]['instanceType'][0])
509 dsdb_dn
.binary
= "%08X" % int(res
[0]['instanceType'][0])
511 if str(dsdb_dn
) != val
:
513 self
.err_incorrect_binary_dn(obj
.dn
, attrname
, val
, dsdb_dn
, "incorrect instanceType part of Binary DN")
516 # now we have two cases - the source object might or might not be deleted
517 is_deleted
= 'isDeleted' in obj
and obj
['isDeleted'][0].upper() == 'TRUE'
518 target_is_deleted
= 'isDeleted' in res
[0] and res
[0]['isDeleted'][0].upper() == 'TRUE'
520 # the target DN is not allowed to be deleted, unless the target DN is the
521 # special Deleted Objects container
522 if target_is_deleted
and not is_deleted
and not self
.is_deleted_objects_dn(dsdb_dn
):
524 self
.err_deleted_dn(obj
.dn
, attrname
, val
, dsdb_dn
, res
[0].dn
)
527 # check the DN matches in string form
528 if res
[0].dn
.extended_str() != dsdb_dn
.dn
.extended_str():
530 self
.err_dn_target_mismatch(obj
.dn
, attrname
, val
, dsdb_dn
,
531 res
[0].dn
, "incorrect string version of DN")
534 if is_deleted
and not target_is_deleted
and reverse_link_name
is not None:
535 revealed_dn
= self
.find_revealed_link(obj
.dn
, attrname
, guid
)
536 rmd_flags
= revealed_dn
.dn
.get_extended_component("RMD_FLAGS")
537 if rmd_flags
is not None and (int(rmd_flags
) & 1) == 0:
538 # the RMD_FLAGS for this link should be 1, as the target is deleted
539 self
.err_incorrect_rmd_flags(obj
, attrname
, revealed_dn
)
542 # check the reverse_link is correct if there should be one
543 if reverse_link_name
is not None:
545 if reverse_link_name
in res
[0]:
546 for v
in res
[0][reverse_link_name
]:
547 if v
== obj
.dn
.extended_str():
552 self
.err_orphaned_backlink(obj
, attrname
, val
, reverse_link_name
, dsdb_dn
.dn
)
554 self
.err_missing_backlink(obj
, attrname
, val
, reverse_link_name
, dsdb_dn
.dn
)
560 def get_originating_time(self
, val
, attid
):
561 '''Read metadata properties and return the originating time for
564 :return: the originating time or 0 if not found
567 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
, str(val
))
570 for o
in repl
.ctr
.array
:
572 return o
.originating_change_time
576 def process_metadata(self
, val
):
577 '''Read metadata properties and list attributes in it'''
581 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
, str(val
))
584 for o
in repl
.ctr
.array
:
585 att
= self
.samdb_schema
.get_lDAPDisplayName_by_attid(o
.attid
)
586 list_att
.append(att
.lower())
591 def fix_metadata(self
, dn
, attr
):
592 '''re-write replPropertyMetaData elements for a single attribute for a
593 object. This is used to fix missing replPropertyMetaData elements'''
594 res
= self
.samdb
.search(base
= dn
, scope
=ldb
.SCOPE_BASE
, attrs
= [attr
],
595 controls
= ["search_options:1:2", "show_recycled:1"])
599 nmsg
[attr
] = ldb
.MessageElement(msg
[attr
], ldb
.FLAG_MOD_REPLACE
, attr
)
600 if self
.do_modify(nmsg
, ["relax:0", "provision:0", "show_recycled:1"],
601 "Failed to fix metadata for attribute %s" % attr
):
602 self
.report("Fixed metadata for attribute %s" % attr
)
604 def ace_get_effective_inherited_type(self
, ace
):
605 if ace
.flags
& security
.SEC_ACE_FLAG_INHERIT_ONLY
:
609 if ace
.type == security
.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT
:
611 elif ace
.type == security
.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT
:
613 elif ace
.type == security
.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT
:
615 elif ace
.type == security
.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT
:
621 if not ace
.object.flags
& security
.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT
:
624 return str(ace
.object.inherited_type
)
626 def lookup_class_schemaIDGUID(self
, cls
):
627 if cls
in self
.class_schemaIDGUID
:
628 return self
.class_schemaIDGUID
[cls
]
630 flt
= "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
631 res
= self
.samdb
.search(base
=self
.schema_dn
,
633 attrs
=["schemaIDGUID"])
634 t
= str(ndr_unpack(misc
.GUID
, res
[0]["schemaIDGUID"][0]))
636 self
.class_schemaIDGUID
[cls
] = t
639 def process_sd(self
, dn
, obj
):
640 sd_attr
= "nTSecurityDescriptor"
641 sd_val
= obj
[sd_attr
]
643 sd
= ndr_unpack(security
.descriptor
, str(sd_val
))
645 is_deleted
= 'isDeleted' in obj
and obj
['isDeleted'][0].upper() == 'TRUE'
647 # we don't fix deleted objects
650 sd_clean
= security
.descriptor()
651 sd_clean
.owner_sid
= sd
.owner_sid
652 sd_clean
.group_sid
= sd
.group_sid
653 sd_clean
.type = sd
.type
654 sd_clean
.revision
= sd
.revision
657 last_inherited_type
= None
660 if sd
.sacl
is not None:
662 for i
in range(0, len(aces
)):
665 if not ace
.flags
& security
.SEC_ACE_FLAG_INHERITED_ACE
:
666 sd_clean
.sacl_add(ace
)
669 t
= self
.ace_get_effective_inherited_type(ace
)
673 if last_inherited_type
is not None:
674 if t
!= last_inherited_type
:
675 # if it inherited from more than
676 # one type it's very likely to be broken
678 # If not the recalculation will calculate
683 last_inherited_type
= t
686 if sd
.dacl
is not None:
688 for i
in range(0, len(aces
)):
691 if not ace
.flags
& security
.SEC_ACE_FLAG_INHERITED_ACE
:
692 sd_clean
.dacl_add(ace
)
695 t
= self
.ace_get_effective_inherited_type(ace
)
699 if last_inherited_type
is not None:
700 if t
!= last_inherited_type
:
701 # if it inherited from more than
702 # one type it's very likely to be broken
704 # If not the recalculation will calculate
709 last_inherited_type
= t
712 return (sd_clean
, sd
)
714 if last_inherited_type
is None:
720 cls
= obj
["objectClass"][-1]
725 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
,
726 attrs
=["isDeleted", "objectClass"],
727 controls
=["show_recycled:1"])
729 is_deleted
= 'isDeleted' in o
and o
['isDeleted'][0].upper() == 'TRUE'
731 # we don't fix deleted objects
733 cls
= o
["objectClass"][-1]
735 t
= self
.lookup_class_schemaIDGUID(cls
)
737 if t
!= last_inherited_type
:
739 return (sd_clean
, sd
)
744 def err_wrong_sd(self
, dn
, sd
, sd_broken
):
745 '''re-write the SD due to incorrect inherited ACEs'''
746 sd_attr
= "nTSecurityDescriptor"
747 sd_val
= ndr_pack(sd
)
748 sd_flags
= security
.SECINFO_DACL | security
.SECINFO_SACL
750 if not self
.confirm_all('Fix %s on %s?' % (sd_attr
, dn
), 'fix_ntsecuritydescriptor'):
751 self
.report('Not fixing %s on %s\n' % (sd_attr
, dn
))
756 nmsg
[sd_attr
] = ldb
.MessageElement(sd_val
, ldb
.FLAG_MOD_REPLACE
, sd_attr
)
757 if self
.do_modify(nmsg
, ["sd_flags:1:%d" % sd_flags
],
758 "Failed to fix attribute %s" % sd_attr
):
759 self
.report("Fixed attribute '%s' of '%s'\n" % (sd_attr
, dn
))
761 def err_wrong_default_sd(self
, dn
, sd
, sd_old
, diff
):
762 '''re-write the SD due to not matching the default (optional mode for fixing an incorrect provision)'''
763 sd_attr
= "nTSecurityDescriptor"
764 sd_val
= ndr_pack(sd
)
765 sd_old_val
= ndr_pack(sd_old
)
766 sd_flags
= security
.SECINFO_DACL | security
.SECINFO_SACL
767 if sd
.owner_sid
is not None:
768 sd_flags |
= security
.SECINFO_OWNER
769 if sd
.group_sid
is not None:
770 sd_flags |
= security
.SECINFO_GROUP
772 if not self
.confirm_all('Reset %s on %s back to provision default?\n%s' % (sd_attr
, dn
, diff
), 'reset_all_well_known_acls'):
773 self
.report('Not resetting %s on %s\n' % (sd_attr
, dn
))
778 m
[sd_attr
] = ldb
.MessageElement(sd_val
, ldb
.FLAG_MOD_REPLACE
, sd_attr
)
779 if self
.do_modify(m
, ["sd_flags:1:%d" % sd_flags
],
780 "Failed to reset attribute %s" % sd_attr
):
781 self
.report("Fixed attribute '%s' of '%s'\n" % (sd_attr
, dn
))
783 def is_fsmo_role(self
, dn
):
784 if dn
== self
.samdb
.domain_dn
:
786 if dn
== self
.infrastructure_dn
:
788 if dn
== self
.naming_dn
:
790 if dn
== self
.schema_dn
:
792 if dn
== self
.rid_dn
:
797 def calculate_instancetype(self
, dn
):
799 nc_root
= self
.samdb
.get_nc_root(dn
)
801 instancetype |
= dsdb
.INSTANCE_TYPE_IS_NC_HEAD
803 self
.samdb
.search(base
=dn
.parent(), scope
=ldb
.SCOPE_BASE
, attrs
=[], controls
=["show_recycled:1"])
804 except ldb
.LdbError
, (enum
, estr
):
805 if enum
!= ldb
.ERR_NO_SUCH_OBJECT
:
808 instancetype |
= dsdb
.INSTANCE_TYPE_NC_ABOVE
810 if self
.write_ncs
is not None and str(nc_root
) in self
.write_ncs
:
811 instancetype |
= dsdb
.INSTANCE_TYPE_WRITE
815 def get_wellknown_sd(self
, dn
):
816 for [sd_dn
, descriptor_fn
] in self
.wellknown_sds
:
818 domain_sid
= security
.dom_sid(self
.samdb
.get_domain_sid())
819 return ndr_unpack(security
.descriptor
,
820 descriptor_fn(domain_sid
,
821 name_map
=self
.name_map
))
825 def check_object(self
, dn
, attrs
=['*']):
826 '''check one object'''
828 self
.report("Checking object %s" % dn
)
830 attrs
.append("replPropertyMetaData")
834 sd_flags |
= security
.SECINFO_OWNER
835 sd_flags |
= security
.SECINFO_GROUP
836 sd_flags |
= security
.SECINFO_DACL
837 sd_flags |
= security
.SECINFO_SACL
839 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
,
844 "sd_flags:1:%d" % sd_flags
,
847 except ldb
.LdbError
, (enum
, estr
):
848 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
849 if self
.in_transaction
:
850 self
.report("ERROR: Object %s disappeared during check" % dn
)
855 self
.report("ERROR: Object %s failed to load during check" % dn
)
859 list_attrs_from_md
= []
861 got_repl_property_meta_data
= False
867 if str(attrname
).lower() == 'replpropertymetadata':
868 list_attrs_from_md
= self
.process_metadata(obj
[attrname
])
869 got_repl_property_meta_data
= True
872 if str(attrname
).lower() == 'ntsecuritydescriptor':
873 (sd
, sd_broken
) = self
.process_sd(dn
, obj
)
874 if sd_broken
is not None:
875 self
.err_wrong_sd(dn
, sd
, sd_broken
)
879 if self
.reset_well_known_acls
:
881 well_known_sd
= self
.get_wellknown_sd(dn
)
885 current_sd
= ndr_unpack(security
.descriptor
,
886 str(obj
[attrname
][0]))
888 diff
= get_diff_sds(well_known_sd
, current_sd
, security
.dom_sid(self
.samdb
.get_domain_sid()))
890 self
.err_wrong_default_sd(dn
, well_known_sd
, current_sd
, diff
)
895 if str(attrname
).lower() == 'objectclass':
896 normalised
= self
.samdb
.dsdb_normalise_attributes(self
.samdb_schema
, attrname
, list(obj
[attrname
]))
897 if list(normalised
) != list(obj
[attrname
]):
898 self
.err_normalise_mismatch_replace(dn
, attrname
, list(obj
[attrname
]))
902 # check for empty attributes
903 for val
in obj
[attrname
]:
905 self
.err_empty_attribute(dn
, attrname
)
909 # get the syntax oid for the attribute, so we can can have
910 # special handling for some specific attribute types
912 syntax_oid
= self
.samdb_schema
.get_syntax_oid_from_lDAPDisplayName(attrname
)
913 except Exception, msg
:
914 self
.err_unknown_attribute(obj
, attrname
)
918 flag
= self
.samdb_schema
.get_systemFlags_from_lDAPDisplayName(attrname
)
919 if (not flag
& dsdb
.DS_FLAG_ATTR_NOT_REPLICATED
920 and not flag
& dsdb
.DS_FLAG_ATTR_IS_CONSTRUCTED
921 and not self
.samdb_schema
.get_linkId_from_lDAPDisplayName(attrname
)):
922 list_attrs_seen
.append(str(attrname
).lower())
924 if syntax_oid
in [ dsdb
.DSDB_SYNTAX_BINARY_DN
, dsdb
.DSDB_SYNTAX_OR_NAME
,
925 dsdb
.DSDB_SYNTAX_STRING_DN
, ldb
.SYNTAX_DN
]:
926 # it's some form of DN, do specialised checking on those
927 error_count
+= self
.check_dn(obj
, attrname
, syntax_oid
)
929 # check for incorrectly normalised attributes
930 for val
in obj
[attrname
]:
931 normalised
= self
.samdb
.dsdb_normalise_attributes(self
.samdb_schema
, attrname
, [val
])
932 if len(normalised
) != 1 or normalised
[0] != val
:
933 self
.err_normalise_mismatch(dn
, attrname
, obj
[attrname
])
937 if str(attrname
).lower() == "instancetype":
938 calculated_instancetype
= self
.calculate_instancetype(dn
)
939 if len(obj
["instanceType"]) != 1 or obj
["instanceType"][0] != str(calculated_instancetype
):
940 self
.err_wrong_instancetype(obj
, calculated_instancetype
)
943 if got_repl_property_meta_data
:
944 rdn
= (str(dn
).split(","))[0]
945 if rdn
== "CN=Deleted Objects":
946 isDeletedAttId
= 131120
947 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
949 expectedTimeDo
= 2650466015990000000
950 originating
= self
.get_originating_time(obj
["replPropertyMetaData"], isDeletedAttId
)
951 if originating
!= expectedTimeDo
:
952 if self
.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn
), 'fix_time_metadata'):
955 nmsg
["isDeleted"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isDeleted")
957 self
.samdb
.modify(nmsg
, controls
=["provision:0"])
960 self
.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn
))
961 for att
in list_attrs_seen
:
962 if not att
in list_attrs_from_md
:
964 self
.report("On object %s" % dn
)
967 self
.report("ERROR: Attribute %s not present in replication metadata" % att
)
968 if not self
.confirm_all("Fix missing replPropertyMetaData element '%s'" % att
, 'fix_all_metadata'):
969 self
.report("Not fixing missing replPropertyMetaData element '%s'" % att
)
971 self
.fix_metadata(dn
, att
)
973 if self
.is_fsmo_role(dn
):
974 if "fSMORoleOwner" not in obj
:
975 self
.err_no_fsmoRoleOwner(obj
)
979 if dn
!= self
.samdb
.get_root_basedn():
980 res
= self
.samdb
.search(base
=dn
.parent(), scope
=ldb
.SCOPE_BASE
,
981 controls
=["show_recycled:1", "show_deleted:1"])
982 except ldb
.LdbError
, (enum
, estr
):
983 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
984 self
.err_missing_parent(obj
)
991 ################################################################
992 # check special @ROOTDSE attributes
993 def check_rootdse(self
):
994 '''check the @ROOTDSE special object'''
995 dn
= ldb
.Dn(self
.samdb
, '@ROOTDSE')
997 self
.report("Checking object %s" % dn
)
998 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
)
1000 self
.report("Object %s disappeared during check" % dn
)
1005 # check that the dsServiceName is in GUID form
1006 if not 'dsServiceName' in obj
:
1007 self
.report('ERROR: dsServiceName missing in @ROOTDSE')
1008 return error_count
+1
1010 if not obj
['dsServiceName'][0].startswith('<GUID='):
1011 self
.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
1013 if not self
.confirm('Change dsServiceName to GUID form?'):
1015 res
= self
.samdb
.search(base
=ldb
.Dn(self
.samdb
, obj
['dsServiceName'][0]),
1016 scope
=ldb
.SCOPE_BASE
, attrs
=['objectGUID'])
1017 guid_str
= str(ndr_unpack(misc
.GUID
, res
[0]['objectGUID'][0]))
1020 m
['dsServiceName'] = ldb
.MessageElement("<GUID=%s>" % guid_str
,
1021 ldb
.FLAG_MOD_REPLACE
, 'dsServiceName')
1022 if self
.do_modify(m
, [], "Failed to change dsServiceName to GUID form", validate
=False):
1023 self
.report("Changed dsServiceName to GUID form")
1027 ###############################################
1028 # re-index the database
1029 def reindex_database(self
):
1030 '''re-index the whole database'''
1032 m
.dn
= ldb
.Dn(self
.samdb
, "@ATTRIBUTES")
1033 m
['add'] = ldb
.MessageElement('NONE', ldb
.FLAG_MOD_ADD
, 'force_reindex')
1034 m
['delete'] = ldb
.MessageElement('NONE', ldb
.FLAG_MOD_DELETE
, 'force_reindex')
1035 return self
.do_modify(m
, [], 're-indexed database', validate
=False)
1037 ###############################################
1039 def reset_modules(self
):
1040 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
1042 m
.dn
= ldb
.Dn(self
.samdb
, "@MODULES")
1043 m
['@LIST'] = ldb
.MessageElement('samba_dsdb', ldb
.FLAG_MOD_REPLACE
, '@LIST')
1044 return self
.do_modify(m
, [], 'reset @MODULES on database', validate
=False)