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