s4-samba-tool: dbcheck, check and fix broken metadata
[metze/samba/wip.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
29
30 class dsdb_DN(object):
31     '''a class to manipulate DN components'''
32
33     def __init__(self, samdb, dnstring, syntax_oid):
34         if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_STRING_DN ]:
35             colons = dnstring.split(':')
36             if len(colons) < 4:
37                 raise Exception("invalid DN prefix")
38             prefix_len = 4 + len(colons[1]) + int(colons[1])
39             self.prefix = dnstring[0:prefix_len]
40             self.dnstring = dnstring[prefix_len:]
41         else:
42             self.dnstring = dnstring
43             self.prefix = ''
44         try:
45             self.dn = ldb.Dn(samdb, self.dnstring)
46         except Exception, msg:
47             print("ERROR: bad DN string '%s'" % self.dnstring)
48             raise
49
50     def __str__(self):
51         return self.prefix + str(self.dn.extended_str(mode=1))
52
53 class dbcheck(object):
54     """check a SAM database for errors"""
55
56     def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, yes=False, quiet=False):
57         self.samdb = samdb
58         self.dict_oid_name = None
59         self.samdb_schema = (samdb_schema or samdb)
60         self.verbose = verbose
61         self.fix = fix
62         self.yes = yes
63         self.quiet = quiet
64         self.remove_all_unknown_attributes = False
65         self.remove_all_empty_attributes = False
66         self.fix_all_normalisation = False
67         self.fix_all_DN_GUIDs = False
68         self.remove_all_deleted_DN_links = False
69         self.fix_all_target_mismatch = False
70
71     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
72         '''perform a database check, returning the number of errors found'''
73
74         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
75         self.report('Checking %u objects' % len(res))
76         error_count = 0
77         for object in res:
78             error_count += self.check_object(object.dn, attrs=attrs)
79         if error_count != 0 and not self.fix:
80             self.report("Please use --fix to fix these errors")
81         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
82
83         return error_count
84
85
86     def report(self, msg):
87         '''print a message unless quiet is set'''
88         if not self.quiet:
89             print(msg)
90
91
92     ################################################################
93     # a local confirm function that obeys the --fix and --yes options
94     def confirm(self, msg, allow_all=False, forced=False):
95         '''confirm a change'''
96         if not self.fix:
97             return False
98         if self.quiet:
99             return self.yes
100         if self.yes:
101             forced = True
102         return common.confirm(msg, forced=forced, allow_all=allow_all)
103
104     ################################################################
105     # a local confirm function with support for 'all'
106     def confirm_all(self, msg, all_attr):
107         '''confirm a change with support for "all" '''
108         if not self.fix:
109             return False
110         if self.quiet:
111             return self.yes
112         if getattr(self, all_attr) == 'NONE':
113             return False
114         if getattr(self, all_attr) == 'ALL':
115             forced = True
116         else:
117             forced = self.yes
118         c = common.confirm(msg, forced=forced, allow_all=True)
119         if c == 'ALL':
120             setattr(self, all_attr, 'ALL')
121             return True
122         if c == 'NONE':
123             setattr(self, all_attr, 'NONE')
124             return True
125         return c
126
127
128     ################################################################
129     # handle empty attributes
130     def err_empty_attribute(self, dn, attrname):
131         '''fix empty attributes'''
132         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
133         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
134             self.report("Not fixing empty attribute %s" % attrname)
135             return
136
137         m = ldb.Message()
138         m.dn = dn
139         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
140         if self.verbose:
141             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
142         try:
143             self.samdb.modify(m, controls=["relax:0", "show_deleted:1"], validate=False)
144         except Exception, msg:
145             self.report("Failed to remove empty attribute %s : %s" % (attrname, msg))
146             return
147         self.report("Removed empty attribute %s" % attrname)
148
149
150     ################################################################
151     # handle normalisation mismatches
152     def err_normalise_mismatch(self, dn, attrname, values):
153         '''fix attribute normalisation errors'''
154         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
155         mod_list = []
156         for val in values:
157             normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
158             if len(normalised) != 1:
159                 self.report("Unable to normalise value '%s'" % val)
160                 mod_list.append((val, ''))
161             elif (normalised[0] != val):
162                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
163                 mod_list.append((val, normalised[0]))
164         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
165             self.report("Not fixing attribute %s" % attrname)
166             return
167
168         m = ldb.Message()
169         m.dn = dn
170         for i in range(0, len(mod_list)):
171             (val, nval) = mod_list[i]
172             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
173             if nval != '':
174                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
175
176         if self.verbose:
177             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
178         try:
179             self.samdb.modify(m, controls=["relax:0", "show_deleted:1"], validate=False)
180         except Exception, msg:
181             self.report("Failed to normalise attribute %s : %s" % (attrname, msg))
182             return
183         self.report("Normalised attribute %s" % attrname)
184
185     def is_deleted_objects_dn(self, dsdb_dn):
186         '''see if a dsdb_DN is the special Deleted Objects DN'''
187         return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
188
189
190     ################################################################
191     # handle a missing GUID extended DN component
192     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
193         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
194         controls=["extended_dn:1:1", "show_deleted:1"]
195         try:
196             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
197                                     attrs=[], controls=controls)
198         except ldb.LdbError, (enum, estr):
199             self.report("unable to find object for DN %s - cannot fix (%s)" % (dsdb_dn.dn, estr))
200             return
201         dsdb_dn.dn = res[0].dn
202
203         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
204             self.report("Not fixing %s" % errstr)
205             return
206         m = ldb.Message()
207         m.dn = dn
208         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
209         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
210         if self.verbose:
211             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
212         try:
213             self.samdb.modify(m, controls=["show_deleted:1"])
214         except Exception, msg:
215             self.report("Failed to fix %s on attribute %s : %s" % (errstr, attrname, msg))
216             return
217         self.report("Fixed %s on attribute %s" % (errstr, attrname))
218
219
220     ################################################################
221     # handle a DN pointing to a deleted object
222     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
223         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
224         self.report("Target GUID points at deleted DN %s" % correct_dn)
225         if not self.confirm_all('Remove DN?', 'remove_all_deleted_DN_links'):
226             self.report("Not removing")
227             return
228         m = ldb.Message()
229         m.dn = dn
230         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
231         if self.verbose:
232             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
233         try:
234             self.samdb.modify(m, controls=["show_deleted:1"])
235         except Exception, msg:
236             self.report("Failed to remove deleted DN attribute %s : %s" % (attrname, msg))
237             return
238         self.report("Removed deleted DN on attribute %s" % attrname)
239
240
241     ################################################################
242     # handle a DN string being incorrect
243     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
244         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
245         dsdb_dn.dn = correct_dn
246
247         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
248             self.report("Not fixing %s" % errstr)
249             return
250         m = ldb.Message()
251         m.dn = dn
252         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
253         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
254         if self.verbose:
255             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
256         try:
257             self.samdb.modify(m, controls=["show_deleted:1"])
258         except Exception, msg:
259             self.report("Failed to fix incorrect DN string on attribute %s : %s" % (attrname, msg))
260             return
261         self.report("Fixed incorrect DN string on attribute %s" % (attrname))
262
263     ################################################################
264     # handle an unknown attribute error
265     def err_unknown_attribute(self, obj, attrname):
266         '''handle an unknown attribute error'''
267         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
268         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
269             self.report("Not removing %s" % attrname)
270             return
271         m = ldb.Message()
272         m.dn = obj.dn
273         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
274         if self.verbose:
275             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
276         try:
277             self.samdb.modify(m, controls=["relax:0", "show_deleted:1"])
278         except Exception, msg:
279             self.report("Failed to remove unknown attribute %s : %s" % (attrname, msg))
280             return
281         self.report("Removed unknown attribute %s" % (attrname))
282
283
284     ################################################################
285     # specialised checking for a dn attribute
286     def check_dn(self, obj, attrname, syntax_oid):
287         '''check a DN attribute for correctness'''
288         error_count = 0
289         for val in obj[attrname]:
290             dsdb_dn = dsdb_DN(self.samdb, val, syntax_oid)
291
292             # all DNs should have a GUID component
293             guid = dsdb_dn.dn.get_extended_component("GUID")
294             if guid is None:
295                 error_count += 1
296                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
297                 continue
298
299             guidstr = str(misc.GUID(guid))
300
301             # check its the right GUID
302             try:
303                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
304                                         attrs=['isDeleted'], controls=["extended_dn:1:1", "show_deleted:1"])
305             except ldb.LdbError, (enum, estr):
306                 error_count += 1
307                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
308                 continue
309
310             # now we have two cases - the source object might or might not be deleted
311             is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
312             target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
313
314             # the target DN is not allowed to be deleted, unless the target DN is the
315             # special Deleted Objects container
316             if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
317                 error_count += 1
318                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
319                 continue
320
321             # check the DN matches in string form
322             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
323                 error_count += 1
324                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
325                                             res[0].dn, "incorrect string version of DN")
326                 continue
327
328         return error_count
329
330
331     def process_metadata(self, val):
332         '''Read metadata properties and list attributes in it'''
333
334         list_att = []
335         d = {}
336         if self.dict_oid_name == None:
337             res = self.samdb.search(expression = '(lDAPDisplayName=*)',
338                                     controls=["search_options:1:2"],
339                                     attrs=["attributeID","lDAPDisplayName"])
340             for m in res:
341                 d[str(m.get("attributeID"))] = str(m.get("lDAPDisplayName"))
342             self.dict_oid_name = d
343
344         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,str(val))
345         obj = repl.ctr
346
347         for o in repl.ctr.array:
348             att = self.dict_oid_name[self.samdb.get_oid_from_attid(o.attid)]
349             list_att.append(att.lower())
350
351         return list_att
352
353
354     def fix_metadata(self, dn, list):
355         res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = list,
356                 controls = ["search_options:1:2"])
357         msg = res[0]
358         nmsg = ldb.Message()
359
360         delta = self.samdb.msg_diff(nmsg, msg)
361         nmsg.dn = dn
362
363         for att in delta:
364             if att == "dn":
365                 continue
366             val = delta.get(att)
367             nmsg[att] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE, att)
368
369         self.samdb.modify(nmsg, controls = ["relax:0", "provision:0"])
370
371     ################################################################
372     # check one object - calls to individual error handlers above
373     def check_object(self, dn, attrs=['*']):
374         '''check one object'''
375         if self.verbose:
376             self.report("Checking object %s" % dn)
377         if '*' in attrs:
378             attrs.append("replPropertyMetaData")
379
380         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
381                                 controls=["extended_dn:1:1", "show_deleted:1"],
382                                 attrs=attrs)
383         if len(res) != 1:
384             self.report("Object %s disappeared during check" % dn)
385             return 1
386         obj = res[0]
387         error_count = 0
388         list_attrs_from_md = []
389         list_attrs_seen = []
390
391         for attrname in obj:
392             if attrname == 'dn':
393                 continue
394
395             if str(attrname).lower() == 'replpropertymetadata':
396                 list_attrs_from_md = self.process_metadata(obj[attrname])
397                 continue
398
399
400             # check for empty attributes
401             for val in obj[attrname]:
402                 if val == '':
403                     self.err_empty_attribute(dn, attrname)
404                     error_count += 1
405                     continue
406
407             # get the syntax oid for the attribute, so we can can have
408             # special handling for some specific attribute types
409             try:
410                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
411             except Exception, msg:
412                 self.err_unknown_attribute(obj, attrname)
413                 error_count += 1
414                 continue
415
416             flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
417             if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
418                 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
419                 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
420                 list_attrs_seen.append(str(attrname).lower())
421
422             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
423                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.LDB_SYNTAX_DN ]:
424                 # it's some form of DN, do specialised checking on those
425                 error_count += self.check_dn(obj, attrname, syntax_oid)
426
427             # check for incorrectly normalised attributes
428             for val in obj[attrname]:
429                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
430                 if len(normalised) != 1 or normalised[0] != val:
431                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
432                     error_count += 1
433                     break
434
435         show_dn = True
436         if len(list_attrs_seen):
437             attrs_to_fix = []
438             for att in list_attrs_seen:
439                 if not att in list_attrs_from_md:
440                     if show_dn:
441                         print "On object %s" % dn
442                         show_dn = False
443                     print " Attribute %s not present in replication metadata" % (att)
444                     error_count += 1
445                     attrs_to_fix.append(att)
446
447             if len(attrs_to_fix) and self.fix:
448                 self.fix_metadata(dn, attrs_to_fix)
449
450
451         return error_count