samba-tool dbcheck: Use dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER rather than the litera...
[nivanova/samba-autobuild/.git] / python / samba / dbchecker.py
1 # Samba4 AD database checker
2 #
3 # Copyright (C) Andrew Tridgell 2011
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
5 #
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.
10 #
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.
15 #
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/>.
18 #
19
20 import ldb
21 from samba import dsdb
22 from samba import common
23 from samba.dcerpc import misc
24 from samba.ndr import ndr_unpack, ndr_pack
25 from samba.dcerpc import drsblobs
26 from samba.common import dsdb_Dn
27 from samba.dcerpc import security
28 from samba.descriptor import get_wellknown_sds, get_diff_sds
29 from samba.auth import system_session, admin_session
30
31
32 class dbcheck(object):
33     """check a SAM database for errors"""
34
35     def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
36                  yes=False, quiet=False, in_transaction=False,
37                  reset_well_known_acls=False):
38         self.samdb = samdb
39         self.dict_oid_name = None
40         self.samdb_schema = (samdb_schema or samdb)
41         self.verbose = verbose
42         self.fix = fix
43         self.yes = yes
44         self.quiet = quiet
45         self.remove_all_unknown_attributes = False
46         self.remove_all_empty_attributes = False
47         self.fix_all_normalisation = False
48         self.fix_all_DN_GUIDs = False
49         self.fix_all_binary_dn = False
50         self.remove_all_deleted_DN_links = False
51         self.fix_all_target_mismatch = False
52         self.fix_all_metadata = False
53         self.fix_time_metadata = False
54         self.fix_all_missing_backlinks = False
55         self.fix_all_orphaned_backlinks = False
56         self.fix_rmd_flags = False
57         self.fix_ntsecuritydescriptor = False
58         self.fix_ntsecuritydescriptor_owner_group = False
59         self.seize_fsmo_role = False
60         self.move_to_lost_and_found = False
61         self.fix_instancetype = False
62         self.reset_well_known_acls = reset_well_known_acls
63         self.reset_all_well_known_acls = False
64         self.in_transaction = in_transaction
65         self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
66         self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
67         self.schema_dn = samdb.get_schema_basedn()
68         self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
69         self.ntds_dsa = ldb.Dn(samdb, samdb.get_dsServiceName())
70         self.class_schemaIDGUID = {}
71         self.wellknown_sds = get_wellknown_sds(self.samdb)
72
73         self.name_map = {}
74         try:
75             res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % samdb.domain_dn(), scope=ldb.SCOPE_BASE,
76                            attrs=["objectSid"])
77             dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
78             self.name_map['DnsAdmins'] = str(dnsadmins_sid)
79         except ldb.LdbError, (enum, estr):
80             if enum != ldb.ERR_NO_SUCH_OBJECT:
81                 raise
82             pass
83
84         self.system_session_info = system_session()
85         self.admin_session_info = admin_session(None, samdb.get_domain_sid())
86
87         res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs'])
88         if "msDS-hasMasterNCs" in res[0]:
89             self.write_ncs = res[0]["msDS-hasMasterNCs"]
90         else:
91             # If the Forest Level is less than 2003 then there is no
92             # msDS-hasMasterNCs, so we fall back to hasMasterNCs
93             # no need to merge as all the NCs that are in hasMasterNCs must
94             # also be in msDS-hasMasterNCs (but not the opposite)
95             if "hasMasterNCs" in res[0]:
96                 self.write_ncs = res[0]["hasMasterNCs"]
97             else:
98                 self.write_ncs = None
99
100
101     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
102         '''perform a database check, returning the number of errors found'''
103
104         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
105         self.report('Checking %u objects' % len(res))
106         error_count = 0
107
108         for object in res:
109             error_count += self.check_object(object.dn, attrs=attrs)
110
111         if DN is None:
112             error_count += self.check_rootdse()
113
114         if error_count != 0 and not self.fix:
115             self.report("Please use --fix to fix these errors")
116
117         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
118         return error_count
119
120     def report(self, msg):
121         '''print a message unless quiet is set'''
122         if not self.quiet:
123             print(msg)
124
125     def confirm(self, msg, allow_all=False, forced=False):
126         '''confirm a change'''
127         if not self.fix:
128             return False
129         if self.quiet:
130             return self.yes
131         if self.yes:
132             forced = True
133         return common.confirm(msg, forced=forced, allow_all=allow_all)
134
135     ################################################################
136     # a local confirm function with support for 'all'
137     def confirm_all(self, msg, all_attr):
138         '''confirm a change with support for "all" '''
139         if not self.fix:
140             return False
141         if self.quiet:
142             return self.yes
143         if getattr(self, all_attr) == 'NONE':
144             return False
145         if getattr(self, all_attr) == 'ALL':
146             forced = True
147         else:
148             forced = self.yes
149         c = common.confirm(msg, forced=forced, allow_all=True)
150         if c == 'ALL':
151             setattr(self, all_attr, 'ALL')
152             return True
153         if c == 'NONE':
154             setattr(self, all_attr, 'NONE')
155             return False
156         return c
157
158     def do_modify(self, m, controls, msg, validate=True):
159         '''perform a modify with optional verbose output'''
160         if self.verbose:
161             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
162         try:
163             controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
164             self.samdb.modify(m, controls=controls, validate=validate)
165         except Exception, err:
166             self.report("%s : %s" % (msg, err))
167             return False
168         return True
169
170     def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
171         '''perform a modify with optional verbose output'''
172         if self.verbose:
173             self.report("""dn: %s
174 changeType: modrdn
175 newrdn: %s
176 deleteOldRdn: 1
177 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
178         try:
179             to_dn = to_rdn + to_base
180             controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
181             self.samdb.rename(from_dn, to_dn, controls=controls)
182         except Exception, err:
183             self.report("%s : %s" % (msg, err))
184             return False
185         return True
186
187     def err_empty_attribute(self, dn, attrname):
188         '''fix empty attributes'''
189         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
190         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
191             self.report("Not fixing empty attribute %s" % attrname)
192             return
193
194         m = ldb.Message()
195         m.dn = dn
196         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
197         if self.do_modify(m, ["relax:0", "show_recycled:1"],
198                           "Failed to remove empty attribute %s" % attrname, validate=False):
199             self.report("Removed empty attribute %s" % attrname)
200
201     def err_normalise_mismatch(self, dn, attrname, values):
202         '''fix attribute normalisation errors'''
203         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
204         mod_list = []
205         for val in values:
206             normalised = self.samdb.dsdb_normalise_attributes(
207                 self.samdb_schema, attrname, [val])
208             if len(normalised) != 1:
209                 self.report("Unable to normalise value '%s'" % val)
210                 mod_list.append((val, ''))
211             elif (normalised[0] != val):
212                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
213                 mod_list.append((val, normalised[0]))
214         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
215             self.report("Not fixing attribute %s" % attrname)
216             return
217
218         m = ldb.Message()
219         m.dn = dn
220         for i in range(0, len(mod_list)):
221             (val, nval) = mod_list[i]
222             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
223             if nval != '':
224                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
225                     attrname)
226
227         if self.do_modify(m, ["relax:0", "show_recycled:1"],
228                           "Failed to normalise attribute %s" % attrname,
229                           validate=False):
230             self.report("Normalised attribute %s" % attrname)
231
232     def err_normalise_mismatch_replace(self, dn, attrname, values):
233         '''fix attribute normalisation errors'''
234         normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
235         self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
236         self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
237         if list(normalised) == values:
238             return
239         if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
240             self.report("Not fixing attribute '%s'" % attrname)
241             return
242
243         m = ldb.Message()
244         m.dn = dn
245         m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
246
247         if self.do_modify(m, ["relax:0", "show_recycled:1"],
248                           "Failed to normalise attribute %s" % attrname,
249                           validate=False):
250             self.report("Normalised attribute %s" % attrname)
251
252     def is_deleted_objects_dn(self, dsdb_dn):
253         '''see if a dsdb_Dn is the special Deleted Objects DN'''
254         return dsdb_dn.prefix == "B:32:%s:" % dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER
255
256     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
257         """handle a DN pointing to a deleted object"""
258         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
259         self.report("Target GUID points at deleted DN %s" % correct_dn)
260         if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
261             self.report("Not removing")
262             return
263         m = ldb.Message()
264         m.dn = dn
265         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
266         if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
267                           "Failed to remove deleted DN attribute %s" % attrname):
268             self.report("Removed deleted DN on attribute %s" % attrname)
269
270     def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
271         """handle a missing target DN (both GUID and DN string form are missing)"""
272         # check if its a backlink
273         linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
274         if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
275             self.report("Not removing dangling forward link")
276             return
277         self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
278
279     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
280         """handle a missing GUID extended DN component"""
281         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
282         controls=["extended_dn:1:1", "show_recycled:1"]
283         try:
284             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
285                                     attrs=[], controls=controls)
286         except ldb.LdbError, (enum, estr):
287             self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
288             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
289             return
290         if len(res) == 0:
291             self.report("unable to find object for DN %s" % dsdb_dn.dn)
292             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
293             return
294         dsdb_dn.dn = res[0].dn
295
296         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
297             self.report("Not fixing %s" % errstr)
298             return
299         m = ldb.Message()
300         m.dn = dn
301         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
302         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
303
304         if self.do_modify(m, ["show_recycled:1"],
305                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
306             self.report("Fixed %s on attribute %s" % (errstr, attrname))
307
308     def err_incorrect_binary_dn(self, dn, attrname, val, dsdb_dn, errstr):
309         """handle an incorrect binary DN component"""
310         self.report("ERROR: %s binary component for %s in object %s - %s" % (errstr, attrname, dn, val))
311         controls=["extended_dn:1:1", "show_recycled:1"]
312
313         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_binary_dn'):
314             self.report("Not fixing %s" % errstr)
315             return
316         m = ldb.Message()
317         m.dn = dn
318         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
319         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
320
321         if self.do_modify(m, ["show_recycled:1"],
322                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
323             self.report("Fixed %s on attribute %s" % (errstr, attrname))
324
325     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
326         """handle a DN string being incorrect"""
327         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
328         dsdb_dn.dn = correct_dn
329
330         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
331             self.report("Not fixing %s" % errstr)
332             return
333         m = ldb.Message()
334         m.dn = dn
335         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
336         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
337         if self.do_modify(m, ["show_recycled:1"],
338                           "Failed to fix incorrect DN string on attribute %s" % attrname):
339             self.report("Fixed incorrect DN string on attribute %s" % (attrname))
340
341     def err_unknown_attribute(self, obj, attrname):
342         '''handle an unknown attribute error'''
343         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
344         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
345             self.report("Not removing %s" % attrname)
346             return
347         m = ldb.Message()
348         m.dn = obj.dn
349         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
350         if self.do_modify(m, ["relax:0", "show_recycled:1"],
351                           "Failed to remove unknown attribute %s" % attrname):
352             self.report("Removed unknown attribute %s" % (attrname))
353
354     def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
355         '''handle a missing backlink value'''
356         self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
357         if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
358             self.report("Not fixing missing backlink %s" % backlink_name)
359             return
360         m = ldb.Message()
361         m.dn = obj.dn
362         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
363         m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
364         if self.do_modify(m, ["show_recycled:1"],
365                           "Failed to fix missing backlink %s" % backlink_name):
366             self.report("Fixed missing backlink %s" % (backlink_name))
367
368     def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
369         '''handle a incorrect RMD_FLAGS value'''
370         rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
371         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()))
372         if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
373             self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
374             return
375         m = ldb.Message()
376         m.dn = obj.dn
377         m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
378         if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
379                           "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
380             self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
381
382     def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
383         '''handle a orphaned backlink value'''
384         self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
385         if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
386             self.report("Not removing orphaned backlink %s" % link_name)
387             return
388         m = ldb.Message()
389         m.dn = obj.dn
390         m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
391         if self.do_modify(m, ["show_recycled:1", "relax:0"],
392                           "Failed to fix orphaned backlink %s" % link_name):
393             self.report("Fixed orphaned backlink %s" % (link_name))
394
395     def err_no_fsmoRoleOwner(self, obj):
396         '''handle a missing fSMORoleOwner'''
397         self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
398         res = self.samdb.search("",
399                                 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
400         assert len(res) == 1
401         serviceName = res[0]["dsServiceName"][0]
402         if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
403             self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
404             return
405         m = ldb.Message()
406         m.dn = obj.dn
407         m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
408         if self.do_modify(m, [],
409                           "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
410             self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
411
412     def err_missing_parent(self, obj):
413         '''handle a missing parent'''
414         self.report("ERROR: parent object not found for %s" % (obj.dn))
415         if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
416             self.report('Not moving object %s into LostAndFound' % (obj.dn))
417             return
418
419         keep_transaction = True
420         self.samdb.transaction_start()
421         try:
422             nc_root = self.samdb.get_nc_root(obj.dn);
423             lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
424             new_dn = ldb.Dn(self.samdb, str(obj.dn))
425             new_dn.remove_base_components(len(new_dn) - 1)
426             if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
427                               "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
428                 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
429
430                 m = ldb.Message()
431                 m.dn = obj.dn
432                 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
433
434                 if self.do_modify(m, [],
435                                   "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
436                     self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
437                     keep_transaction = True
438         except:
439             self.samdb.transaction_cancel()
440             raise
441
442         if keep_transaction:
443             self.samdb.transaction_commit()
444         else:
445             self.samdb.transaction_cancel()
446
447
448     def err_wrong_instancetype(self, obj, calculated_instancetype):
449         '''handle a wrong instanceType'''
450         self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
451         if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
452             self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
453             return
454
455         m = ldb.Message()
456         m.dn = obj.dn
457         m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
458         if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
459                           "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
460             self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
461
462     def find_revealed_link(self, dn, attrname, guid):
463         '''return a revealed link in an object'''
464         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
465                                 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
466         syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
467         for val in res[0][attrname]:
468             dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
469             guid2 = dsdb_dn.dn.get_extended_component("GUID")
470             if guid == guid2:
471                 return dsdb_dn
472         return None
473
474     def check_dn(self, obj, attrname, syntax_oid):
475         '''check a DN attribute for correctness'''
476         error_count = 0
477         for val in obj[attrname]:
478             dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
479
480             # all DNs should have a GUID component
481             guid = dsdb_dn.dn.get_extended_component("GUID")
482             if guid is None:
483                 error_count += 1
484                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
485                     "missing GUID")
486                 continue
487
488             guidstr = str(misc.GUID(guid))
489
490             attrs = ['isDeleted']
491
492             if (str(attrname).lower() == 'msds-hasinstantiatedncs') and (obj.dn == self.ntds_dsa):
493                 fixing_msDS_HasInstantiatedNCs = True
494                 attrs.append("instanceType")
495             else:
496                 fixing_msDS_HasInstantiatedNCs = False
497
498             linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
499             reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
500             if reverse_link_name is not None:
501                 attrs.append(reverse_link_name)
502
503             # check its the right GUID
504             try:
505                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
506                                         attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
507             except ldb.LdbError, (enum, estr):
508                 error_count += 1
509                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
510                 continue
511
512             if fixing_msDS_HasInstantiatedNCs:
513                 dsdb_dn.prefix = "B:8:%08X:" % int(res[0]['instanceType'][0])
514                 dsdb_dn.binary = "%08X" % int(res[0]['instanceType'][0])
515
516                 if str(dsdb_dn) != val:
517                     error_count +=1
518                     self.err_incorrect_binary_dn(obj.dn, attrname, val, dsdb_dn, "incorrect instanceType part of Binary DN")
519                     continue
520
521             # now we have two cases - the source object might or might not be deleted
522             is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
523             target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
524
525             # the target DN is not allowed to be deleted, unless the target DN is the
526             # special Deleted Objects container
527             if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
528                 error_count += 1
529                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
530                 continue
531
532             # check the DN matches in string form
533             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
534                 error_count += 1
535                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
536                                             res[0].dn, "incorrect string version of DN")
537                 continue
538
539             if is_deleted and not target_is_deleted and reverse_link_name is not None:
540                 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
541                 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
542                 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
543                     # the RMD_FLAGS for this link should be 1, as the target is deleted
544                     self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
545                     continue
546
547             # check the reverse_link is correct if there should be one
548             if reverse_link_name is not None:
549                 match_count = 0
550                 if reverse_link_name in res[0]:
551                     for v in res[0][reverse_link_name]:
552                         if v == obj.dn.extended_str():
553                             match_count += 1
554                 if match_count != 1:
555                     error_count += 1
556                     if linkID & 1:
557                         self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
558                     else:
559                         self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
560                     continue
561
562         return error_count
563
564
565     def get_originating_time(self, val, attid):
566         '''Read metadata properties and return the originating time for
567            a given attributeId.
568
569            :return: the originating time or 0 if not found
570         '''
571
572         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
573         obj = repl.ctr
574
575         for o in repl.ctr.array:
576             if o.attid == attid:
577                 return o.originating_change_time
578
579         return 0
580
581     def process_metadata(self, val):
582         '''Read metadata properties and list attributes in it'''
583
584         list_att = []
585
586         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
587         obj = repl.ctr
588
589         for o in repl.ctr.array:
590             att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
591             list_att.append(att.lower())
592
593         return list_att
594
595
596     def fix_metadata(self, dn, attr):
597         '''re-write replPropertyMetaData elements for a single attribute for a
598         object. This is used to fix missing replPropertyMetaData elements'''
599         res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
600                                 controls = ["search_options:1:2", "show_recycled:1"])
601         msg = res[0]
602         nmsg = ldb.Message()
603         nmsg.dn = dn
604         nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
605         if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
606                           "Failed to fix metadata for attribute %s" % attr):
607             self.report("Fixed metadata for attribute %s" % attr)
608
609     def ace_get_effective_inherited_type(self, ace):
610         if ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY:
611             return None
612
613         check = False
614         if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT:
615             check = True
616         elif ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT:
617             check = True
618         elif ace.type == security.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT:
619             check = True
620         elif ace.type == security.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT:
621             check = True
622
623         if not check:
624             return None
625
626         if not ace.object.flags & security.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT:
627             return None
628
629         return str(ace.object.inherited_type)
630
631     def lookup_class_schemaIDGUID(self, cls):
632         if cls in self.class_schemaIDGUID:
633             return self.class_schemaIDGUID[cls]
634
635         flt = "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
636         res = self.samdb.search(base=self.schema_dn,
637                                 expression=flt,
638                                 attrs=["schemaIDGUID"])
639         t = str(ndr_unpack(misc.GUID, res[0]["schemaIDGUID"][0]))
640
641         self.class_schemaIDGUID[cls] = t
642         return t
643
644     def process_sd(self, dn, obj):
645         sd_attr = "nTSecurityDescriptor"
646         sd_val = obj[sd_attr]
647
648         sd = ndr_unpack(security.descriptor, str(sd_val))
649
650         is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
651         if is_deleted:
652             # we don't fix deleted objects
653             return (sd, None)
654
655         sd_clean = security.descriptor()
656         sd_clean.owner_sid = sd.owner_sid
657         sd_clean.group_sid = sd.group_sid
658         sd_clean.type = sd.type
659         sd_clean.revision = sd.revision
660
661         broken = False
662         last_inherited_type = None
663
664         aces = []
665         if sd.sacl is not None:
666             aces = sd.sacl.aces
667         for i in range(0, len(aces)):
668             ace = aces[i]
669
670             if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
671                 sd_clean.sacl_add(ace)
672                 continue
673
674             t = self.ace_get_effective_inherited_type(ace)
675             if t is None:
676                 continue
677
678             if last_inherited_type is not None:
679                 if t != last_inherited_type:
680                     # if it inherited from more than
681                     # one type it's very likely to be broken
682                     #
683                     # If not the recalculation will calculate
684                     # the same result.
685                     broken = True
686                 continue
687
688             last_inherited_type = t
689
690         aces = []
691         if sd.dacl is not None:
692             aces = sd.dacl.aces
693         for i in range(0, len(aces)):
694             ace = aces[i]
695
696             if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
697                 sd_clean.dacl_add(ace)
698                 continue
699
700             t = self.ace_get_effective_inherited_type(ace)
701             if t is None:
702                 continue
703
704             if last_inherited_type is not None:
705                 if t != last_inherited_type:
706                     # if it inherited from more than
707                     # one type it's very likely to be broken
708                     #
709                     # If not the recalculation will calculate
710                     # the same result.
711                     broken = True
712                 continue
713
714             last_inherited_type = t
715
716         if broken:
717             return (sd_clean, sd)
718
719         if last_inherited_type is None:
720             # ok
721             return (sd, None)
722
723         cls = None
724         try:
725             cls = obj["objectClass"][-1]
726         except KeyError, e:
727             pass
728
729         if cls is None:
730             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
731                                     attrs=["isDeleted", "objectClass"],
732                                     controls=["show_recycled:1"])
733             o = res[0]
734             is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE'
735             if is_deleted:
736                 # we don't fix deleted objects
737                 return (sd, None)
738             cls = o["objectClass"][-1]
739
740         t = self.lookup_class_schemaIDGUID(cls)
741
742         if t != last_inherited_type:
743             # broken
744             return (sd_clean, sd)
745
746         # ok
747         return (sd, None)
748
749     def err_wrong_sd(self, dn, sd, sd_broken):
750         '''re-write the SD due to incorrect inherited ACEs'''
751         sd_attr = "nTSecurityDescriptor"
752         sd_val = ndr_pack(sd)
753         sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
754
755         if not self.confirm_all('Fix %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor'):
756             self.report('Not fixing %s on %s\n' % (sd_attr, dn))
757             return
758
759         nmsg = ldb.Message()
760         nmsg.dn = dn
761         nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
762         if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
763                           "Failed to fix attribute %s" % sd_attr):
764             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
765
766     def err_wrong_default_sd(self, dn, sd, sd_old, diff):
767         '''re-write the SD due to not matching the default (optional mode for fixing an incorrect provision)'''
768         sd_attr = "nTSecurityDescriptor"
769         sd_val = ndr_pack(sd)
770         sd_old_val = ndr_pack(sd_old)
771         sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
772         if sd.owner_sid is not None:
773             sd_flags |= security.SECINFO_OWNER
774         if sd.group_sid is not None:
775             sd_flags |= security.SECINFO_GROUP
776
777         if not self.confirm_all('Reset %s on %s back to provision default?\n%s' % (sd_attr, dn, diff), 'reset_all_well_known_acls'):
778             self.report('Not resetting %s on %s\n' % (sd_attr, dn))
779             return
780
781         m = ldb.Message()
782         m.dn = dn
783         m[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
784         if self.do_modify(m, ["sd_flags:1:%d" % sd_flags],
785                           "Failed to reset attribute %s" % sd_attr):
786             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
787
788     def err_missing_sd_owner(self, dn, sd):
789         '''re-write the SD due to a missing owner or group'''
790         sd_attr = "nTSecurityDescriptor"
791         sd_val = ndr_pack(sd)
792         sd_flags = security.SECINFO_OWNER | security.SECINFO_GROUP
793
794         if not self.confirm_all('Fix missing owner or group in %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor_owner_group'):
795             self.report('Not fixing missing owner or group %s on %s\n' % (sd_attr, dn))
796             return
797
798         nmsg = ldb.Message()
799         nmsg.dn = dn
800         nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
801
802         # By setting the session_info to admin_session_info and
803         # setting the security.SECINFO_OWNER | security.SECINFO_GROUP
804         # flags we cause the descriptor module to set the correct
805         # owner and group on the SD, replacing the None/NULL values
806         # for owner_sid and group_sid currently present.
807         #
808         # The admin_session_info matches that used in provision, and
809         # is the best guess we can make for an existing object that
810         # hasn't had something specifically set.
811         #
812         # This is important for the dns related naming contexts.
813         self.samdb.set_session_info(self.admin_session_info)
814         if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
815                           "Failed to fix metadata for attribute %s" % sd_attr):
816             self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
817         self.samdb.set_session_info(self.system_session_info)
818
819     def is_fsmo_role(self, dn):
820         if dn == self.samdb.domain_dn:
821             return True
822         if dn == self.infrastructure_dn:
823             return True
824         if dn == self.naming_dn:
825             return True
826         if dn == self.schema_dn:
827             return True
828         if dn == self.rid_dn:
829             return True
830
831         return False
832
833     def calculate_instancetype(self, dn):
834         instancetype = 0
835         nc_root = self.samdb.get_nc_root(dn)
836         if dn == nc_root:
837             instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
838             try:
839                 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
840             except ldb.LdbError, (enum, estr):
841                 if enum != ldb.ERR_NO_SUCH_OBJECT:
842                     raise
843             else:
844                 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
845
846         if self.write_ncs is not None and str(nc_root) in self.write_ncs:
847             instancetype |= dsdb.INSTANCE_TYPE_WRITE
848
849         return instancetype
850
851     def get_wellknown_sd(self, dn):
852         for [sd_dn, descriptor_fn] in self.wellknown_sds:
853             if dn == sd_dn:
854                 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
855                 return ndr_unpack(security.descriptor,
856                                   descriptor_fn(domain_sid,
857                                                 name_map=self.name_map))
858
859         raise KeyError
860
861     def check_object(self, dn, attrs=['*']):
862         '''check one object'''
863         if self.verbose:
864             self.report("Checking object %s" % dn)
865         if '*' in attrs:
866             attrs.append("replPropertyMetaData")
867
868         try:
869             sd_flags = 0
870             sd_flags |= security.SECINFO_OWNER
871             sd_flags |= security.SECINFO_GROUP
872             sd_flags |= security.SECINFO_DACL
873             sd_flags |= security.SECINFO_SACL
874
875             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
876                                     controls=[
877                                         "extended_dn:1:1",
878                                         "show_recycled:1",
879                                         "show_deleted:1",
880                                         "sd_flags:1:%d" % sd_flags,
881                                     ],
882                                     attrs=attrs)
883         except ldb.LdbError, (enum, estr):
884             if enum == ldb.ERR_NO_SUCH_OBJECT:
885                 if self.in_transaction:
886                     self.report("ERROR: Object %s disappeared during check" % dn)
887                     return 1
888                 return 0
889             raise
890         if len(res) != 1:
891             self.report("ERROR: Object %s failed to load during check" % dn)
892             return 1
893         obj = res[0]
894         error_count = 0
895         list_attrs_from_md = []
896         list_attrs_seen = []
897         got_repl_property_meta_data = False
898
899         for attrname in obj:
900             if attrname == 'dn':
901                 continue
902
903             if str(attrname).lower() == 'replpropertymetadata':
904                 list_attrs_from_md = self.process_metadata(obj[attrname])
905                 got_repl_property_meta_data = True
906                 continue
907
908             if str(attrname).lower() == 'ntsecuritydescriptor':
909                 (sd, sd_broken) = self.process_sd(dn, obj)
910                 if sd_broken is not None:
911                     self.err_wrong_sd(dn, sd, sd_broken)
912                     error_count += 1
913                     continue
914
915                 if sd.owner_sid is None or sd.group_sid is None:
916                     self.err_missing_sd_owner(dn, sd)
917                     error_count += 1
918                     continue
919
920                 if self.reset_well_known_acls:
921                     try:
922                         well_known_sd = self.get_wellknown_sd(dn)
923                     except KeyError:
924                         continue
925
926                     current_sd = ndr_unpack(security.descriptor,
927                                             str(obj[attrname][0]))
928
929                     diff = get_diff_sds(well_known_sd, current_sd, security.dom_sid(self.samdb.get_domain_sid()))
930                     if diff != "":
931                         self.err_wrong_default_sd(dn, well_known_sd, current_sd, diff)
932                         error_count += 1
933                         continue
934                 continue
935
936             if str(attrname).lower() == 'objectclass':
937                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
938                 if list(normalised) != list(obj[attrname]):
939                     self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
940                     error_count += 1
941                 continue
942
943             # check for empty attributes
944             for val in obj[attrname]:
945                 if val == '':
946                     self.err_empty_attribute(dn, attrname)
947                     error_count += 1
948                     continue
949
950             # get the syntax oid for the attribute, so we can can have
951             # special handling for some specific attribute types
952             try:
953                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
954             except Exception, msg:
955                 self.err_unknown_attribute(obj, attrname)
956                 error_count += 1
957                 continue
958
959             flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
960             if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
961                 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
962                 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
963                 list_attrs_seen.append(str(attrname).lower())
964
965             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
966                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
967                 # it's some form of DN, do specialised checking on those
968                 error_count += self.check_dn(obj, attrname, syntax_oid)
969
970             # check for incorrectly normalised attributes
971             for val in obj[attrname]:
972                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
973                 if len(normalised) != 1 or normalised[0] != val:
974                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
975                     error_count += 1
976                     break
977
978             if str(attrname).lower() == "instancetype":
979                 calculated_instancetype = self.calculate_instancetype(dn)
980                 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
981                     self.err_wrong_instancetype(obj, calculated_instancetype)
982
983         show_dn = True
984         if got_repl_property_meta_data:
985             rdn = (str(dn).split(","))[0]
986             if rdn == "CN=Deleted Objects":
987                 isDeletedAttId = 131120
988                 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
989
990                 expectedTimeDo = 2650466015990000000
991                 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
992                 if originating != expectedTimeDo:
993                     if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
994                         nmsg = ldb.Message()
995                         nmsg.dn = dn
996                         nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
997                         error_count += 1
998                         self.samdb.modify(nmsg, controls=["provision:0"])
999
1000                     else:
1001                         self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
1002             for att in list_attrs_seen:
1003                 if not att in list_attrs_from_md:
1004                     if show_dn:
1005                         self.report("On object %s" % dn)
1006                         show_dn = False
1007                     error_count += 1
1008                     self.report("ERROR: Attribute %s not present in replication metadata" % att)
1009                     if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
1010                         self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
1011                         continue
1012                     self.fix_metadata(dn, att)
1013
1014         if self.is_fsmo_role(dn):
1015             if "fSMORoleOwner" not in obj:
1016                 self.err_no_fsmoRoleOwner(obj)
1017                 error_count += 1
1018
1019         try:
1020             if dn != self.samdb.get_root_basedn():
1021                 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
1022                                         controls=["show_recycled:1", "show_deleted:1"])
1023         except ldb.LdbError, (enum, estr):
1024             if enum == ldb.ERR_NO_SUCH_OBJECT:
1025                 self.err_missing_parent(obj)
1026                 error_count += 1
1027             else:
1028                 raise
1029
1030         return error_count
1031
1032     ################################################################
1033     # check special @ROOTDSE attributes
1034     def check_rootdse(self):
1035         '''check the @ROOTDSE special object'''
1036         dn = ldb.Dn(self.samdb, '@ROOTDSE')
1037         if self.verbose:
1038             self.report("Checking object %s" % dn)
1039         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
1040         if len(res) != 1:
1041             self.report("Object %s disappeared during check" % dn)
1042             return 1
1043         obj = res[0]
1044         error_count = 0
1045
1046         # check that the dsServiceName is in GUID form
1047         if not 'dsServiceName' in obj:
1048             self.report('ERROR: dsServiceName missing in @ROOTDSE')
1049             return error_count+1
1050
1051         if not obj['dsServiceName'][0].startswith('<GUID='):
1052             self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
1053             error_count += 1
1054             if not self.confirm('Change dsServiceName to GUID form?'):
1055                 return error_count
1056             res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
1057                                     scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
1058             guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
1059             m = ldb.Message()
1060             m.dn = dn
1061             m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
1062                                                     ldb.FLAG_MOD_REPLACE, 'dsServiceName')
1063             if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
1064                 self.report("Changed dsServiceName to GUID form")
1065         return error_count
1066
1067
1068     ###############################################
1069     # re-index the database
1070     def reindex_database(self):
1071         '''re-index the whole database'''
1072         m = ldb.Message()
1073         m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
1074         m['add']    = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
1075         m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
1076         return self.do_modify(m, [], 're-indexed database', validate=False)
1077
1078     ###############################################
1079     # reset @MODULES
1080     def reset_modules(self):
1081         '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
1082         m = ldb.Message()
1083         m.dn = ldb.Dn(self.samdb, "@MODULES")
1084         m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
1085         return self.do_modify(m, [], 'reset @MODULES on database', validate=False)