s4-dsdb: moved dsdb_Dn() into common.py
[rusty/samba.git] / source4 / scripting / python / samba / dbchecker.py
1 #!/usr/bin/env python
2 #
3 # Samba4 AD database checker
4 #
5 # Copyright (C) Andrew Tridgell 2011
6 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21
22 import ldb
23 from samba import dsdb
24 from samba import common
25 from samba.dcerpc import misc
26 from samba.ndr import ndr_unpack
27 from samba.dcerpc import drsblobs
28 from samba.common import dsdb_Dn
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, yes=False, quiet=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_all_missing_backlinks = False
49         self.fix_all_orphaned_backlinks = False
50
51     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
52         '''perform a database check, returning the number of errors found'''
53
54         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
55         self.report('Checking %u objects' % len(res))
56         error_count = 0
57
58         for object in res:
59             error_count += self.check_object(object.dn, attrs=attrs)
60
61         if DN is None:
62             error_count += self.check_rootdse()
63
64         if error_count != 0 and not self.fix:
65             self.report("Please use --fix to fix these errors")
66
67
68         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
69
70         return error_count
71
72
73     def report(self, msg):
74         '''print a message unless quiet is set'''
75         if not self.quiet:
76             print(msg)
77
78
79     ################################################################
80     # a local confirm function that obeys the --fix and --yes options
81     def confirm(self, msg, allow_all=False, forced=False):
82         '''confirm a change'''
83         if not self.fix:
84             return False
85         if self.quiet:
86             return self.yes
87         if self.yes:
88             forced = True
89         return common.confirm(msg, forced=forced, allow_all=allow_all)
90
91     ################################################################
92     # a local confirm function with support for 'all'
93     def confirm_all(self, msg, all_attr):
94         '''confirm a change with support for "all" '''
95         if not self.fix:
96             return False
97         if self.quiet:
98             return self.yes
99         if getattr(self, all_attr) == 'NONE':
100             return False
101         if getattr(self, all_attr) == 'ALL':
102             forced = True
103         else:
104             forced = self.yes
105         c = common.confirm(msg, forced=forced, allow_all=True)
106         if c == 'ALL':
107             setattr(self, all_attr, 'ALL')
108             return True
109         if c == 'NONE':
110             setattr(self, all_attr, 'NONE')
111             return True
112         return c
113
114
115     def do_modify(self, m, controls, msg, validate=True):
116         '''perform a modify with optional verbose output'''
117         if self.verbose:
118             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
119         try:
120             self.samdb.modify(m, controls=controls, validate=validate)
121         except Exception, err:
122             self.report("%s : %s" % (msg, err))
123             return False
124         return True
125
126
127     ################################################################
128     # handle empty attributes
129     def err_empty_attribute(self, dn, attrname):
130         '''fix empty attributes'''
131         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
132         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
133             self.report("Not fixing empty attribute %s" % attrname)
134             return
135
136         m = ldb.Message()
137         m.dn = dn
138         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
139         if self.do_modify(m, ["relax:0", "show_recycled:1"],
140                           "Failed to remove empty attribute %s" % attrname, validate=False):
141             self.report("Removed empty attribute %s" % attrname)
142
143
144     ################################################################
145     # handle normalisation mismatches
146     def err_normalise_mismatch(self, dn, attrname, values):
147         '''fix attribute normalisation errors'''
148         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
149         mod_list = []
150         for val in values:
151             normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
152             if len(normalised) != 1:
153                 self.report("Unable to normalise value '%s'" % val)
154                 mod_list.append((val, ''))
155             elif (normalised[0] != val):
156                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
157                 mod_list.append((val, normalised[0]))
158         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
159             self.report("Not fixing attribute %s" % attrname)
160             return
161
162         m = ldb.Message()
163         m.dn = dn
164         for i in range(0, len(mod_list)):
165             (val, nval) = mod_list[i]
166             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
167             if nval != '':
168                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
169
170         if self.do_modify(m, ["relax:0", "show_recycled:1"],
171                           "Failed to normalise attribute %s" % attrname,
172                           validate=False):
173             self.report("Normalised attribute %s" % attrname)
174
175     def is_deleted_objects_dn(self, dsdb_dn):
176         '''see if a dsdb_Dn is the special Deleted Objects DN'''
177         return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
178
179
180     ################################################################
181     # handle a DN pointing to a deleted object
182     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
183         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
184         self.report("Target GUID points at deleted DN %s" % correct_dn)
185         if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
186             self.report("Not removing")
187             return
188         m = ldb.Message()
189         m.dn = dn
190         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
191         if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
192                           "Failed to remove deleted DN attribute %s" % attrname):
193             self.report("Removed deleted DN on attribute %s" % attrname)
194
195     ################################################################
196     # handle a missing target DN (both GUID and DN string form are missing)
197     def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
198         # check if its a backlink
199         linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
200         if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
201             self.report("Not removing dangling forward link")
202             return
203         self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
204
205
206     ################################################################
207     # handle a missing GUID extended DN component
208     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
209         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
210         controls=["extended_dn:1:1", "show_recycled:1"]
211         try:
212             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
213                                     attrs=[], controls=controls)
214         except ldb.LdbError, (enum, estr):
215             self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
216             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
217             return
218         if len(res) == 0:
219             self.report("unable to find object for DN %s" % dsdb_dn.dn)
220             self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
221             return
222         dsdb_dn.dn = res[0].dn
223
224         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
225             self.report("Not fixing %s" % errstr)
226             return
227         m = ldb.Message()
228         m.dn = dn
229         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
230         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
231
232         if self.do_modify(m, ["show_recycled:1"],
233                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
234             self.report("Fixed %s on attribute %s" % (errstr, attrname))
235
236
237     ################################################################
238     # handle a DN string being incorrect
239     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
240         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
241         dsdb_dn.dn = correct_dn
242
243         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
244             self.report("Not fixing %s" % errstr)
245             return
246         m = ldb.Message()
247         m.dn = dn
248         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
249         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
250         if self.do_modify(m, ["show_recycled:1"],
251                           "Failed to fix incorrect DN string on attribute %s" % attrname):
252             self.report("Fixed incorrect DN string on attribute %s" % (attrname))
253
254     ################################################################
255     # handle an unknown attribute error
256     def err_unknown_attribute(self, obj, attrname):
257         '''handle an unknown attribute error'''
258         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
259         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
260             self.report("Not removing %s" % attrname)
261             return
262         m = ldb.Message()
263         m.dn = obj.dn
264         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
265         if self.do_modify(m, ["relax:0", "show_recycled:1"],
266                           "Failed to remove unknown attribute %s" % attrname):
267             self.report("Removed unknown attribute %s" % (attrname))
268
269
270     ################################################################
271     # handle a missing backlink
272     def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
273         '''handle a missing backlink value'''
274         self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
275         if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
276             self.report("Not fixing missing backlink %s" % backlink_name)
277             return
278         m = ldb.Message()
279         m.dn = obj.dn
280         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
281         m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
282         if self.do_modify(m, ["show_recycled:1"],
283                           "Failed to fix missing backlink %s" % backlink_name):
284             self.report("Fixed missing backlink %s" % (backlink_name))
285
286
287     ################################################################
288     # handle a orphaned backlink
289     def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
290         '''handle a orphaned backlink value'''
291         self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
292         if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
293             self.report("Not removing orphaned backlink %s" % link_name)
294             return
295         m = ldb.Message()
296         m.dn = obj.dn
297         m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
298         if self.do_modify(m, ["show_recycled:1", "relax:0"],
299                           "Failed to fix orphaned backlink %s" % link_name):
300             self.report("Fixed orphaned backlink %s" % (link_name))
301
302
303     ################################################################
304     # specialised checking for a dn attribute
305     def check_dn(self, obj, attrname, syntax_oid):
306         '''check a DN attribute for correctness'''
307         error_count = 0
308         for val in obj[attrname]:
309             dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
310
311             # all DNs should have a GUID component
312             guid = dsdb_dn.dn.get_extended_component("GUID")
313             if guid is None:
314                 error_count += 1
315                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
316                 continue
317
318             guidstr = str(misc.GUID(guid))
319
320             attrs=['isDeleted']
321             linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
322             reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
323             if reverse_link_name is not None:
324                 attrs.append(reverse_link_name)
325
326             # check its the right GUID
327             try:
328                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
329                                         attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
330             except ldb.LdbError, (enum, estr):
331                 error_count += 1
332                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
333                 continue
334
335             # now we have two cases - the source object might or might not be deleted
336             is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
337             target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
338
339             # the target DN is not allowed to be deleted, unless the target DN is the
340             # special Deleted Objects container
341             if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
342                 error_count += 1
343                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
344                 continue
345
346             # check the DN matches in string form
347             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
348                 error_count += 1
349                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
350                                             res[0].dn, "incorrect string version of DN")
351                 continue
352
353             # check the reverse_link is correct if there should be one
354             if reverse_link_name is not None:
355                 match_count = 0
356                 if reverse_link_name in res[0]:
357                     for v in res[0][reverse_link_name]:
358                         if v == obj.dn.extended_str():
359                             match_count += 1
360                 if match_count != 1:
361                     error_count += 1
362                     if linkID & 1:
363                         self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
364                     else:
365                         self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
366                     continue
367
368         return error_count
369
370
371     def process_metadata(self, val):
372         '''Read metadata properties and list attributes in it'''
373
374         list_att = []
375
376         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
377         obj = repl.ctr
378
379         for o in repl.ctr.array:
380             att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
381             list_att.append(att.lower())
382
383         return list_att
384
385
386     def fix_metadata(self, dn, attr):
387         '''re-write replPropertyMetaData elements for a single attribute for a
388         object. This is used to fix missing replPropertyMetaData elements'''
389         res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
390                                 controls = ["search_options:1:2", "show_recycled:1"])
391         msg = res[0]
392         nmsg = ldb.Message()
393         nmsg.dn = dn
394         nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
395         if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
396                           "Failed to fix metadata for attribute %s" % attr):
397             self.report("Fixed metadata for attribute %s" % attr)
398
399
400     ################################################################
401     # check one object - calls to individual error handlers above
402     def check_object(self, dn, attrs=['*']):
403         '''check one object'''
404         if self.verbose:
405             self.report("Checking object %s" % dn)
406         if '*' in attrs:
407             attrs.append("replPropertyMetaData")
408
409         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
410                                 controls=["extended_dn:1:1", "show_recycled:1"],
411                                 attrs=attrs)
412         if len(res) != 1:
413             self.report("Object %s disappeared during check" % dn)
414             return 1
415         obj = res[0]
416         error_count = 0
417         list_attrs_from_md = []
418         list_attrs_seen = []
419         got_repl_property_meta_data = False
420
421         for attrname in obj:
422             if attrname == 'dn':
423                 continue
424
425             if str(attrname).lower() == 'replpropertymetadata':
426                 list_attrs_from_md = self.process_metadata(obj[attrname])
427                 got_repl_property_meta_data = True
428                 continue
429
430
431             # check for empty attributes
432             for val in obj[attrname]:
433                 if val == '':
434                     self.err_empty_attribute(dn, attrname)
435                     error_count += 1
436                     continue
437
438             # get the syntax oid for the attribute, so we can can have
439             # special handling for some specific attribute types
440             try:
441                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
442             except Exception, msg:
443                 self.err_unknown_attribute(obj, attrname)
444                 error_count += 1
445                 continue
446
447             flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
448             if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
449                 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
450                 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
451                 list_attrs_seen.append(str(attrname).lower())
452
453             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
454                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
455                 # it's some form of DN, do specialised checking on those
456                 error_count += self.check_dn(obj, attrname, syntax_oid)
457
458             # check for incorrectly normalised attributes
459             for val in obj[attrname]:
460                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
461                 if len(normalised) != 1 or normalised[0] != val:
462                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
463                     error_count += 1
464                     break
465
466         show_dn = True
467         if got_repl_property_meta_data:
468             for att in list_attrs_seen:
469                 if not att in list_attrs_from_md:
470                     if show_dn:
471                         self.report("On object %s" % dn)
472                         show_dn = False
473                     error_count += 1
474                     self.report("ERROR: Attribute %s not present in replication metadata" % att)
475                     if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
476                         self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
477                         continue
478                     self.fix_metadata(dn, att)
479
480         return error_count
481
482     ################################################################
483     # check special @ROOTDSE attributes
484     def check_rootdse(self):
485         '''check the @ROOTDSE special object'''
486         dn = ldb.Dn(self.samdb, '@ROOTDSE')
487         if self.verbose:
488             self.report("Checking object %s" % dn)
489         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
490         if len(res) != 1:
491             self.report("Object %s disappeared during check" % dn)
492             return 1
493         obj = res[0]
494         error_count = 0
495
496         # check that the dsServiceName is in GUID form
497         if not 'dsServiceName' in obj:
498             self.report('ERROR: dsServiceName missing in @ROOTDSE')
499             return error_count+1
500
501         if not obj['dsServiceName'][0].startswith('<GUID='):
502             self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
503             error_count += 1
504             if not self.confirm('Change dsServiceName to GUID form?'):
505                 return error_count
506             res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
507                                     scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
508             guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
509             m = ldb.Message()
510             m.dn = dn
511             m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
512                                                     ldb.FLAG_MOD_REPLACE, 'dsServiceName')
513             if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
514                 self.report("Changed dsServiceName to GUID form")
515         return error_count
516
517
518     ###############################################
519     # re-index the database
520     def reindex_database(self):
521         '''re-index the whole database'''
522         m = ldb.Message()
523         m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
524         m['add']    = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
525         m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
526         return self.do_modify(m, [], 're-indexed database', validate=False)