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
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):
36 self
.dict_oid_name
= None
37 self
.samdb_schema
= (samdb_schema
or samdb
)
38 self
.verbose
= verbose
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"]
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"]
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
))
87 error_count
+= self
.check_object(object.dn
, attrs
=attrs
)
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
))
98 def report(self
, msg
):
99 '''print a message unless quiet is set'''
103 def confirm(self
, msg
, allow_all
=False, forced
=False):
104 '''confirm a change'''
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" '''
121 if getattr(self
, all_attr
) == 'NONE':
123 if getattr(self
, all_attr
) == 'ALL':
127 c
= common
.confirm(msg
, forced
=forced
, allow_all
=True)
129 setattr(self
, all_attr
, 'ALL')
132 setattr(self
, all_attr
, 'NONE')
136 def do_modify(self
, m
, controls
, msg
, validate
=True):
137 '''perform a modify with optional verbose output'''
139 self
.report(self
.samdb
.write_ldif(m
, ldb
.CHANGETYPE_MODIFY
))
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
))
148 def do_rename(self
, from_dn
, to_rdn
, to_base
, controls
, msg
):
149 '''perform a modify with optional verbose output'''
151 self
.report("""dn: %s
155 newSuperior: %s""" % (str(from_dn
), str(to_rdn
), str(to_base
)))
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
))
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
)
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
))
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
)
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
)
202 m
['normv_%u' % i
] = ldb
.MessageElement(nval
, ldb
.FLAG_MOD_ADD
,
205 if self
.do_modify(m
, ["relax:0", "show_recycled:1"],
206 "Failed to normalise attribute %s" % attrname
,
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
:
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
)
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
,
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")
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")
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"]
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
)
269 self
.report("unable to find object for DN %s" % dsdb_dn
.dn
)
270 self
.err_missing_dn_GUID(dn
, attrname
, val
, dsdb_dn
)
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
)
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
)
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
)
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
)
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
)
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
)
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"])
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
))
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
))
380 keep_transaction
= True
381 self
.samdb
.transaction_start()
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
))
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
400 self
.samdb
.transaction_cancel()
404 self
.samdb
.transaction_commit()
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
))
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")
435 def check_dn(self
, obj
, attrname
, syntax_oid
):
436 '''check a DN attribute for correctness'''
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")
445 self
.err_incorrect_dn_GUID(obj
.dn
, attrname
, val
, dsdb_dn
,
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
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
):
463 self
.err_incorrect_dn_GUID(obj
.dn
, attrname
, val
, dsdb_dn
, "incorrect GUID")
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
):
474 self
.err_deleted_dn(obj
.dn
, attrname
, val
, dsdb_dn
, res
[0].dn
)
477 # check the DN matches in string form
478 if res
[0].dn
.extended_str() != dsdb_dn
.dn
.extended_str():
480 self
.err_dn_target_mismatch(obj
.dn
, attrname
, val
, dsdb_dn
,
481 res
[0].dn
, "incorrect string version of DN")
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
)
492 # check the reverse_link is correct if there should be one
493 if reverse_link_name
is not None:
495 if reverse_link_name
in res
[0]:
496 for v
in res
[0][reverse_link_name
]:
497 if v
== obj
.dn
.extended_str():
502 self
.err_orphaned_backlink(obj
, attrname
, val
, reverse_link_name
, dsdb_dn
.dn
)
504 self
.err_missing_backlink(obj
, attrname
, val
, reverse_link_name
, dsdb_dn
.dn
)
510 def get_originating_time(self
, val
, attid
):
511 '''Read metadata properties and return the originating time for
514 :return: the originating time or 0 if not found
517 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
, str(val
))
520 for o
in repl
.ctr
.array
:
522 return o
.originating_change_time
526 def process_metadata(self
, val
):
527 '''Read metadata properties and list attributes in it'''
531 repl
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
, str(val
))
534 for o
in repl
.ctr
.array
:
535 att
= self
.samdb_schema
.get_lDAPDisplayName_by_attid(o
.attid
)
536 list_att
.append(att
.lower())
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"])
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
:
559 if ace
.type == security
.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT
:
561 elif ace
.type == security
.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT
:
563 elif ace
.type == security
.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT
:
565 elif ace
.type == security
.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT
:
571 if not ace
.object.flags
& security
.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT
:
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
,
583 attrs
=["schemaIDGUID"])
584 t
= str(ndr_unpack(misc
.GUID
, res
[0]["schemaIDGUID"][0]))
586 self
.class_schemaIDGUID
[cls
] = 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'
597 # we don't fix deleted objects
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
607 last_inherited_type
= None
610 if sd
.sacl
is not None:
612 for i
in range(0, len(aces
)):
615 if not ace
.flags
& security
.SEC_ACE_FLAG_INHERITED_ACE
:
616 sd_clean
.sacl_add(ace
)
619 t
= self
.ace_get_effective_inherited_type(ace
)
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
633 last_inherited_type
= t
636 if sd
.dacl
is not None:
638 for i
in range(0, len(aces
)):
641 if not ace
.flags
& security
.SEC_ACE_FLAG_INHERITED_ACE
:
642 sd_clean
.dacl_add(ace
)
645 t
= self
.ace_get_effective_inherited_type(ace
)
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
659 last_inherited_type
= t
662 return (sd_clean
, sd
)
664 if last_inherited_type
is None:
670 cls
= obj
["objectClass"][-1]
675 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
,
676 attrs
=["isDeleted", "objectClass"],
677 controls
=["show_recycled:1"])
679 is_deleted
= 'isDeleted' in o
and o
['isDeleted'][0].upper() == 'TRUE'
681 # we don't fix deleted objects
683 cls
= o
["objectClass"][-1]
685 t
= self
.lookup_class_schemaIDGUID(cls
)
687 if t
!= last_inherited_type
:
689 return (sd_clean
, sd
)
694 def err_wrong_sd(self
, dn
, sd
, sd_broken
):
695 '''re-write the SD due to incorrect inherited ACEs'''
696 sd_attr
= "nTSecurityDescriptor"
697 sd_val
= ndr_pack(sd
)
698 sd_flags
= security
.SECINFO_DACL | security
.SECINFO_SACL
700 if not self
.confirm_all('Fix %s on %s?' % (sd_attr
, dn
), 'fix_ntsecuritydescriptor'):
701 self
.report('Not fixing %s on %s\n' % (sd_attr
, dn
))
706 nmsg
[sd_attr
] = ldb
.MessageElement(sd_val
, ldb
.FLAG_MOD_REPLACE
, sd_attr
)
707 if self
.do_modify(nmsg
, ["sd_flags:1:%d" % sd_flags
],
708 "Failed to fix metadata for attribute %s" % sd_attr
):
709 self
.report("Fixed attribute '%s' of '%s'\n" % (sd_attr
, dn
))
711 def is_fsmo_role(self
, dn
):
712 if dn
== self
.samdb
.domain_dn
:
714 if dn
== self
.infrastructure_dn
:
716 if dn
== self
.naming_dn
:
718 if dn
== self
.schema_dn
:
720 if dn
== self
.rid_dn
:
725 def calculate_instancetype(self
, dn
):
727 nc_root
= self
.samdb
.get_nc_root(dn
)
729 instancetype |
= dsdb
.INSTANCE_TYPE_IS_NC_HEAD
731 self
.samdb
.search(base
=dn
.parent(), scope
=ldb
.SCOPE_BASE
, attrs
=[], controls
=["show_recycled:1"])
732 except ldb
.LdbError
, (enum
, estr
):
733 if enum
!= ldb
.ERR_NO_SUCH_OBJECT
:
736 instancetype |
= dsdb
.INSTANCE_TYPE_NC_ABOVE
738 if self
.write_ncs
is not None and str(nc_root
) in self
.write_ncs
:
739 instancetype |
= dsdb
.INSTANCE_TYPE_WRITE
743 def check_object(self
, dn
, attrs
=['*']):
744 '''check one object'''
746 self
.report("Checking object %s" % dn
)
748 attrs
.append("replPropertyMetaData")
752 sd_flags |
= security
.SECINFO_OWNER
753 sd_flags |
= security
.SECINFO_GROUP
754 sd_flags |
= security
.SECINFO_DACL
755 sd_flags |
= security
.SECINFO_SACL
757 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
,
762 "sd_flags:1:%d" % sd_flags
,
765 except ldb
.LdbError
, (enum
, estr
):
766 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
767 if self
.in_transaction
:
768 self
.report("ERROR: Object %s disappeared during check" % dn
)
773 self
.report("ERROR: Object %s failed to load during check" % dn
)
777 list_attrs_from_md
= []
779 got_repl_property_meta_data
= False
785 if str(attrname
).lower() == 'replpropertymetadata':
786 list_attrs_from_md
= self
.process_metadata(obj
[attrname
])
787 got_repl_property_meta_data
= True
790 if str(attrname
).lower() == 'ntsecuritydescriptor':
791 (sd
, sd_broken
) = self
.process_sd(dn
, obj
)
792 if sd_broken
is not None:
793 self
.err_wrong_sd(dn
, sd
, sd_broken
)
797 if str(attrname
).lower() == 'objectclass':
798 normalised
= self
.samdb
.dsdb_normalise_attributes(self
.samdb_schema
, attrname
, list(obj
[attrname
]))
799 if list(normalised
) != list(obj
[attrname
]):
800 self
.err_normalise_mismatch_replace(dn
, attrname
, list(obj
[attrname
]))
804 # check for empty attributes
805 for val
in obj
[attrname
]:
807 self
.err_empty_attribute(dn
, attrname
)
811 # get the syntax oid for the attribute, so we can can have
812 # special handling for some specific attribute types
814 syntax_oid
= self
.samdb_schema
.get_syntax_oid_from_lDAPDisplayName(attrname
)
815 except Exception, msg
:
816 self
.err_unknown_attribute(obj
, attrname
)
820 flag
= self
.samdb_schema
.get_systemFlags_from_lDAPDisplayName(attrname
)
821 if (not flag
& dsdb
.DS_FLAG_ATTR_NOT_REPLICATED
822 and not flag
& dsdb
.DS_FLAG_ATTR_IS_CONSTRUCTED
823 and not self
.samdb_schema
.get_linkId_from_lDAPDisplayName(attrname
)):
824 list_attrs_seen
.append(str(attrname
).lower())
826 if syntax_oid
in [ dsdb
.DSDB_SYNTAX_BINARY_DN
, dsdb
.DSDB_SYNTAX_OR_NAME
,
827 dsdb
.DSDB_SYNTAX_STRING_DN
, ldb
.SYNTAX_DN
]:
828 # it's some form of DN, do specialised checking on those
829 error_count
+= self
.check_dn(obj
, attrname
, syntax_oid
)
831 # check for incorrectly normalised attributes
832 for val
in obj
[attrname
]:
833 normalised
= self
.samdb
.dsdb_normalise_attributes(self
.samdb_schema
, attrname
, [val
])
834 if len(normalised
) != 1 or normalised
[0] != val
:
835 self
.err_normalise_mismatch(dn
, attrname
, obj
[attrname
])
839 if str(attrname
).lower() == "instancetype":
840 calculated_instancetype
= self
.calculate_instancetype(dn
)
841 if len(obj
["instanceType"]) != 1 or obj
["instanceType"][0] != str(calculated_instancetype
):
842 self
.err_wrong_instancetype(obj
, calculated_instancetype
)
845 if got_repl_property_meta_data
:
846 rdn
= (str(dn
).split(","))[0]
847 if rdn
== "CN=Deleted Objects":
848 isDeletedAttId
= 131120
849 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
851 expectedTimeDo
= 2650466015990000000
852 originating
= self
.get_originating_time(obj
["replPropertyMetaData"], isDeletedAttId
)
853 if originating
!= expectedTimeDo
:
854 if self
.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn
), 'fix_time_metadata'):
857 nmsg
["isDeleted"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isDeleted")
859 self
.samdb
.modify(nmsg
, controls
=["provision:0"])
862 self
.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn
))
863 for att
in list_attrs_seen
:
864 if not att
in list_attrs_from_md
:
866 self
.report("On object %s" % dn
)
869 self
.report("ERROR: Attribute %s not present in replication metadata" % att
)
870 if not self
.confirm_all("Fix missing replPropertyMetaData element '%s'" % att
, 'fix_all_metadata'):
871 self
.report("Not fixing missing replPropertyMetaData element '%s'" % att
)
873 self
.fix_metadata(dn
, att
)
875 if self
.is_fsmo_role(dn
):
876 if "fSMORoleOwner" not in obj
:
877 self
.err_no_fsmoRoleOwner(obj
)
881 if dn
!= self
.samdb
.get_root_basedn():
882 res
= self
.samdb
.search(base
=dn
.parent(), scope
=ldb
.SCOPE_BASE
,
883 controls
=["show_recycled:1", "show_deleted:1"])
884 except ldb
.LdbError
, (enum
, estr
):
885 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
886 self
.err_missing_parent(obj
)
893 ################################################################
894 # check special @ROOTDSE attributes
895 def check_rootdse(self
):
896 '''check the @ROOTDSE special object'''
897 dn
= ldb
.Dn(self
.samdb
, '@ROOTDSE')
899 self
.report("Checking object %s" % dn
)
900 res
= self
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
)
902 self
.report("Object %s disappeared during check" % dn
)
907 # check that the dsServiceName is in GUID form
908 if not 'dsServiceName' in obj
:
909 self
.report('ERROR: dsServiceName missing in @ROOTDSE')
912 if not obj
['dsServiceName'][0].startswith('<GUID='):
913 self
.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
915 if not self
.confirm('Change dsServiceName to GUID form?'):
917 res
= self
.samdb
.search(base
=ldb
.Dn(self
.samdb
, obj
['dsServiceName'][0]),
918 scope
=ldb
.SCOPE_BASE
, attrs
=['objectGUID'])
919 guid_str
= str(ndr_unpack(misc
.GUID
, res
[0]['objectGUID'][0]))
922 m
['dsServiceName'] = ldb
.MessageElement("<GUID=%s>" % guid_str
,
923 ldb
.FLAG_MOD_REPLACE
, 'dsServiceName')
924 if self
.do_modify(m
, [], "Failed to change dsServiceName to GUID form", validate
=False):
925 self
.report("Changed dsServiceName to GUID form")
929 ###############################################
930 # re-index the database
931 def reindex_database(self
):
932 '''re-index the whole database'''
934 m
.dn
= ldb
.Dn(self
.samdb
, "@ATTRIBUTES")
935 m
['add'] = ldb
.MessageElement('NONE', ldb
.FLAG_MOD_ADD
, 'force_reindex')
936 m
['delete'] = ldb
.MessageElement('NONE', ldb
.FLAG_MOD_DELETE
, 'force_reindex')
937 return self
.do_modify(m
, [], 're-indexed database', validate
=False)
939 ###############################################
941 def reset_modules(self
):
942 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
944 m
.dn
= ldb
.Dn(self
.samdb
, "@MODULES")
945 m
['@LIST'] = ldb
.MessageElement('samba_dsdb', ldb
.FLAG_MOD_REPLACE
, '@LIST')
946 return self
.do_modify(m
, [], 'reset @MODULES on database', validate
=False)