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