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