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